diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8162feed1e88cda5972a8d25e2a84d4473d56708 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/index.d.ts @@ -0,0 +1,5 @@ +export { Beta, type AnthropicBeta, type BetaAPIError, type BetaAuthenticationError, type BetaBillingError, type BetaError, type BetaErrorResponse, type BetaGatewayTimeoutError, type BetaInvalidRequestError, type BetaNotFoundError, type BetaOverloadedError, type BetaPermissionError, type BetaRateLimitError, } from "./beta.js"; +export { Files, type DeletedFile, type FileMetadata, type FileListParams, type FileDeleteParams, type FileDownloadParams, type FileRetrieveMetadataParams, type FileUploadParams, type FileMetadataPage, } from "./files.js"; +export { Messages, type BetaBase64ImageSource, type BetaBase64PDFSource, type BetaCacheControlEphemeral, type BetaCacheCreation, type BetaCitationCharLocation, type BetaCitationCharLocationParam, type BetaCitationContentBlockLocation, type BetaCitationContentBlockLocationParam, type BetaCitationPageLocation, type BetaCitationPageLocationParam, type BetaCitationWebSearchResultLocationParam, type BetaCitationsConfigParam, type BetaCitationsDelta, type BetaCitationsWebSearchResultLocation, type BetaCodeExecutionOutputBlock, type BetaCodeExecutionOutputBlockParam, type BetaCodeExecutionResultBlock, type BetaCodeExecutionResultBlockParam, type BetaCodeExecutionTool20250522, type BetaCodeExecutionToolResultBlock, type BetaCodeExecutionToolResultBlockContent, type BetaCodeExecutionToolResultBlockParam, type BetaCodeExecutionToolResultBlockParamContent, type BetaCodeExecutionToolResultError, type BetaCodeExecutionToolResultErrorCode, type BetaCodeExecutionToolResultErrorParam, type BetaContainer, type BetaContainerUploadBlock, type BetaContainerUploadBlockParam, type BetaContentBlock, type BetaContentBlockParam, type BetaContentBlockSource, type BetaContentBlockSourceContent, type BetaFileDocumentSource, type BetaFileImageSource, type BetaImageBlockParam, type BetaInputJSONDelta, type BetaMCPToolResultBlock, type BetaMCPToolUseBlock, type BetaMCPToolUseBlockParam, type BetaMessage, type BetaMessageDeltaUsage, type BetaMessageParam, type BetaMessageTokensCount, type BetaMetadata, type BetaPlainTextSource, type BetaRawContentBlockDelta, type BetaRawContentBlockDeltaEvent, type BetaRawContentBlockStartEvent, type BetaRawContentBlockStopEvent, type BetaRawMessageDeltaEvent, type BetaRawMessageStartEvent, type BetaRawMessageStopEvent, type BetaRawMessageStreamEvent, type BetaRedactedThinkingBlock, type BetaRedactedThinkingBlockParam, type BetaRequestDocumentBlock, type BetaRequestMCPServerToolConfiguration, type BetaRequestMCPServerURLDefinition, type BetaRequestMCPToolResultBlockParam, type BetaServerToolUsage, type BetaServerToolUseBlock, type BetaServerToolUseBlockParam, type BetaSignatureDelta, type BetaStopReason, type BetaTextBlock, type BetaTextBlockParam, type BetaTextCitation, type BetaTextCitationParam, type BetaTextDelta, type BetaThinkingBlock, type BetaThinkingBlockParam, type BetaThinkingConfigDisabled, type BetaThinkingConfigEnabled, type BetaThinkingConfigParam, type BetaThinkingDelta, type BetaTool, type BetaToolBash20241022, type BetaToolBash20250124, type BetaToolChoice, type BetaToolChoiceAny, type BetaToolChoiceAuto, type BetaToolChoiceNone, type BetaToolChoiceTool, type BetaToolComputerUse20241022, type BetaToolComputerUse20250124, type BetaToolResultBlockParam, type BetaToolTextEditor20241022, type BetaToolTextEditor20250124, type BetaToolTextEditor20250429, type BetaToolUnion, type BetaToolUseBlock, type BetaToolUseBlockParam, type BetaURLImageSource, type BetaURLPDFSource, type BetaUsage, type BetaWebSearchResultBlock, type BetaWebSearchResultBlockParam, type BetaWebSearchTool20250305, type BetaWebSearchToolRequestError, type BetaWebSearchToolResultBlock, type BetaWebSearchToolResultBlockContent, type BetaWebSearchToolResultBlockParam, type BetaWebSearchToolResultBlockParamContent, type BetaWebSearchToolResultError, type BetaWebSearchToolResultErrorCode, type BetaBase64PDFBlock, type MessageCreateParams, type MessageCreateParamsNonStreaming, type MessageCreateParamsStreaming, type MessageCountTokensParams, } from "./messages/index.js"; +export { Models, type BetaModelInfo, type ModelRetrieveParams, type ModelListParams, type BetaModelInfosPage, } from "./models.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.js.map new file mode 100644 index 0000000000000000000000000000000000000000..17245cba3eedaa9e1e0b402129498c19b7ac772e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.js.map @@ -0,0 +1 @@ +{"version":3,"file":"batches.js","sourceRoot":"","sources":["../../../src/resources/beta/messages/batches.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wDAAqD;AAIrD,4DAA8E;AAC9E,0DAAyD;AAEzD,+DAAgE;AAChE,6CAAgD;AAChD,0DAAoD;AAEpD,MAAa,OAAQ,SAAQ,sBAAW;IACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,MAAM,CAAC,MAAyB,EAAE,OAAwB;QACxD,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;QAClC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,gCAAgC,EAAE;YACzD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,IAAA,sBAAY,EAAC;gBACpB,EAAE,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,4BAA4B,CAAC,CAAC,QAAQ,EAAE,EAAE;gBACjF,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OAAO,EAAE,IAAA,sBAAY,EAAC;gBACpB;oBACE,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,4BAA4B,CAAC,CAAC,QAAQ,EAAE;oBAC7E,MAAM,EAAE,oBAAoB;iBAC7B;gBACD,OAAO,EAAE,OAAO;aACjB,CAAC;YACF,MAAM,EAAE,IAAI;YACZ,gBAAgB,EAAE,IAAI;SACvB,CAAC;aACD,WAAW,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,oBAAY,CAAC,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,CAEvF,CAAC;IACJ,CAAC;CACF;AA5ND,0BA4NC"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/index.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9cc40ec5b5883b635e8d4c8e1805ff4e3d2b31cd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/resources/beta/messages/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/beta/messages/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wCAkBmB;AAjBjB,kGAAA,OAAO,OAAA;AAkBT,0CAkHoB;AAjHlB,oGAAA,QAAQ,OAAA"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/README.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bc6ea4e3d180d8f6532fde682535af9e4399bc7f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/README.md @@ -0,0 +1,3 @@ +# Partial JSON Parser + +Vendored from https://www.npmjs.com/package/partial-json-parser and updated to use TypeScript. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/builtin-types.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/builtin-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c23d3bdedc13683a2ad7defc1515539ae2f1b32e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/builtin-types.ts @@ -0,0 +1,93 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise; + +/** + * An alias to the builtin `RequestInit` type so we can + * easily alias it in import statements if there are name clashes. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit + */ +type _RequestInit = RequestInit; + +/** + * An alias to the builtin `Response` type so we can + * easily alias it in import statements if there are name clashes. + * + * https://developer.mozilla.org/docs/Web/API/Response + */ +type _Response = Response; + +/** + * The type for the first argument to `fetch`. + * + * https://developer.mozilla.org/docs/Web/API/Window/fetch#resource + */ +type _RequestInfo = Request | URL | string; + +/** + * The type for constructing `RequestInit` Headers. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit#setting_headers + */ +type _HeadersInit = RequestInit['headers']; + +/** + * The type for constructing `RequestInit` body. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit#body + */ +type _BodyInit = RequestInit['body']; + +/** + * An alias to the builtin `Array` type so we can + * easily alias it in import statements if there are name clashes. + */ +type _Array = Array; + +/** + * An alias to the builtin `Record` type so we can + * easily alias it in import statements if there are name clashes. + */ +type _Record = Record; + +export type { + _Array as Array, + _BodyInit as BodyInit, + _HeadersInit as HeadersInit, + _Record as Record, + _RequestInfo as RequestInfo, + _RequestInit as RequestInit, + _Response as Response, +}; + +/** + * A copy of the builtin `EndingType` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L27941 + */ +type EndingType = 'native' | 'transparent'; + +/** + * A copy of the builtin `BlobPropertyBag` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L154 + * https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#options + */ +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +/** + * A copy of the builtin `FilePropertyBag` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L503 + * https://developer.mozilla.org/en-US/docs/Web/API/File/File#options + */ +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/decoders/jsonl.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/decoders/jsonl.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba0cb8f4ad2ace42a4e6bbeaaaf84b1fb5422f6f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/decoders/jsonl.ts @@ -0,0 +1,48 @@ +import { AnthropicError } from '../../core/error'; +import { ReadableStreamToAsyncIterable } from '../shims'; +import { LineDecoder, type Bytes } from './line'; + +export class JSONLDecoder { + controller: AbortController; + + constructor( + private iterator: AsyncIterableIterator, + controller: AbortController, + ) { + this.controller = controller; + } + + private async *decoder(): AsyncIterator { + const lineDecoder = new LineDecoder(); + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); + } + } + + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); + } + } + + [Symbol.asyncIterator](): AsyncIterator { + return this.decoder(); + } + + static fromResponse(response: Response, controller: AbortController): JSONLDecoder { + if (!response.body) { + controller.abort(); + if ( + typeof (globalThis as any).navigator !== 'undefined' && + (globalThis as any).navigator.product === 'ReactNative' + ) { + throw new AnthropicError( + `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`, + ); + } + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + + return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/types.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7928cd35dc9ac803ca64108fb20b94b6a28401e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/types.ts @@ -0,0 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export type PromiseOrValue = T | Promise; +export type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; + +export type KeysEnum = { [P in keyof Required]: true }; + +export type FinalizedRequestInit = RequestInit & { headers: Headers }; + +type NotAny = [unknown] extends [T] ? never : T; + +/** + * Some environments overload the global fetch function, and Parameters only gets the last signature. + */ +type OverloadedParameters = + T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + (...args: infer D): unknown; + } + ) ? + A | B | C | D + : T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + } + ) ? + A | B | C + : T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + } + ) ? + A | B + : T extends (...args: infer A) => unknown ? A + : never; + +/* eslint-disable */ +/** + * These imports attempt to get types from a parent package's dependencies. + * Unresolved bare specifiers can trigger [automatic type acquisition][1] in some projects, which + * would cause typescript to show types not present at runtime. To avoid this, we import + * directly from parent node_modules folders. + * + * We need to check multiple levels because we don't know what directory structure we'll be in. + * For example, pnpm generates directories like this: + * ``` + * node_modules + * ├── .pnpm + * │ └── pkg@1.0.0 + * │ └── node_modules + * │ └── pkg + * │ └── internal + * │ └── types.d.ts + * ├── pkg -> .pnpm/pkg@1.0.0/node_modules/pkg + * └── undici + * ``` + * + * [1]: https://www.typescriptlang.org/tsconfig/#typeAcquisition + */ +/** @ts-ignore For users with \@types/node */ +type UndiciTypesRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users with undici */ +type UndiciRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users with \@types/bun */ +type BunRequestInit = globalThis.FetchRequestInit; +/** @ts-ignore For users with node-fetch */ +type NodeFetchRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users who use Deno */ +type FetchRequestInit = NonNullable[1]>; +/* eslint-enable */ + +type RequestInits = + | NotAny + | NotAny + | NotAny + | NotAny + | NotAny + | NotAny; + +/** + * This type contains `RequestInit` options that may be available on the current runtime, + * including per-platform extensions like `dispatcher`, `agent`, `client`, etc. + */ +export type MergedRequestInit = RequestInits & + /** We don't include these in the types as they'll be overridden for every request. */ + Partial>; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cbfacce29a05b720a183ce2c4680a40a8463fea --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils.ts @@ -0,0 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './utils/values'; +export * from './utils/base64'; +export * from './utils/env'; +export * from './utils/log'; +export * from './utils/uuid'; +export * from './utils/sleep'; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/bytes.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/bytes.ts new file mode 100644 index 0000000000000000000000000000000000000000..8da627abe133306f787a3d0c4d7182ab3170804b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/bytes.ts @@ -0,0 +1,32 @@ +export function concatBytes(buffers: Uint8Array[]): Uint8Array { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + + return output; +} + +let encodeUTF8_: (str: string) => Uint8Array; +export function encodeUTF8(str: string) { + let encoder; + return ( + encodeUTF8_ ?? + ((encoder = new (globalThis as any).TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))) + )(str); +} + +let decodeUTF8_: (bytes: Uint8Array) => string; +export function decodeUTF8(bytes: Uint8Array) { + let decoder; + return ( + decodeUTF8_ ?? + ((decoder = new (globalThis as any).TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))) + )(bytes); +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/path.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/path.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a7648ca87a321b399561131df316209966aa7d0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/internal/utils/path.ts @@ -0,0 +1,65 @@ +import { AnthropicError } from '../../core/error'; + +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +export function encodeURIPath(str: string) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} + +export const createPathTagFunction = (pathEncoder = encodeURIPath) => + function path(statics: readonly string[], ...params: readonly unknown[]): string { + // If there are no params, no processing is needed. + if (statics.length === 1) return statics[0]!; + + let postPath = false; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + return ( + previousValue + + currentValue + + (index === params.length ? '' : (postPath ? encodeURIComponent : pathEncoder)(String(params[index]))) + ); + }, ''); + + const pathOnly = path.split(/[?#]/, 1)[0]!; + const invalidSegments = []; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + }); + } + + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + + throw new AnthropicError( + `Path parameters result in path with invalid segments:\n${path}\n${underline}`, + ); + } + + return path; + }; + +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +export const path = createPathTagFunction(encodeURIPath); diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ef96edbd1b87c7b081d927fcb88eb3aee14c011 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts @@ -0,0 +1,502 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as BetaAPI from '../beta'; +import { APIPromise } from '../../../core/api-promise'; +import * as BetaMessagesAPI from './messages'; +import { Page, type PageParams, PagePromise } from '../../../core/pagination'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; +import { JSONLDecoder } from '../../../internal/decoders/jsonl'; +import { AnthropicError } from '../../../error'; +import { path } from '../../../internal/utils/path'; + +export class Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-3-7-sonnet-20250219', + * }, + * }, + * ], + * }); + * ``` + */ + create(params: BatchCreateParams, options?: RequestOptions): APIPromise { + const { betas, ...body } = params; + return this._client.post('/v1/messages/batches?beta=true', { + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve( + messageBatchID: string, + params: BatchRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + const { betas } = params ?? {}; + return this._client.get(path`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` + */ + list( + params: BatchListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/messages/batches?beta=true', Page, { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete( + messageBatchID: string, + params: BatchDeleteParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + const { betas } = params ?? {}; + return this._client.delete(path`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel( + messageBatchID: string, + params: BatchCancelParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + const { betas } = params ?? {}; + return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results( + messageBatchID: string, + params: BatchResultsParams | undefined = {}, + options?: RequestOptions, + ): Promise> { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError( + `No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`, + ); + } + + const { betas } = params ?? {}; + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)) as APIPromise< + JSONLDecoder + >; + } +} + +export type BetaMessageBatchesPage = Page; + +export interface BetaDeletedMessageBatch { + /** + * ID of the Message Batch. + */ + id: string; + + /** + * Deleted object type. + * + * For Message Batches, this is always `"message_batch_deleted"`. + */ + type: 'message_batch_deleted'; +} + +export interface BetaMessageBatch { + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + id: string; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was + * archived and its results became unavailable. + */ + archived_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which cancellation was + * initiated for the Message Batch. Specified only if cancellation was initiated. + */ + cancel_initiated_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was + * created. + */ + created_at: string; + + /** + * RFC 3339 datetime string representing the time at which processing for the + * Message Batch ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, + * errored, canceled, or expired. + */ + ended_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will + * expire and end processing, which is 24 hours after creation. + */ + expires_at: string; + + /** + * Processing status of the Message Batch. + */ + processing_status: 'in_progress' | 'canceling' | 'ended'; + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once + * processing of the entire batch ends. The sum of all values always matches the + * total number of requests in the batch. + */ + request_counts: BetaMessageBatchRequestCounts; + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. + * Specified only once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use + * the `custom_id` field to match results to requests. + */ + results_url: string | null; + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + type: 'message_batch'; +} + +export interface BetaMessageBatchCanceledResult { + type: 'canceled'; +} + +export interface BetaMessageBatchErroredResult { + error: BetaAPI.BetaErrorResponse; + + type: 'errored'; +} + +export interface BetaMessageBatchExpiredResult { + type: 'expired'; +} + +/** + * This is a single line in the response `.jsonl` file and does not represent the + * response as a whole. + */ +export interface BetaMessageBatchIndividualResponse { + /** + * Developer-provided ID created for each request in a Message Batch. Useful for + * matching results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + custom_id: string; + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if + * processing failed, or the reason why processing was not attempted, such as + * cancellation or expiration. + */ + result: BetaMessageBatchResult; +} + +export interface BetaMessageBatchRequestCounts { + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + canceled: number; + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + errored: number; + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + expired: number; + + /** + * Number of requests in the Message Batch that are processing. + */ + processing: number; + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + succeeded: number; +} + +/** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if + * processing failed, or the reason why processing was not attempted, such as + * cancellation or expiration. + */ +export type BetaMessageBatchResult = + | BetaMessageBatchSucceededResult + | BetaMessageBatchErroredResult + | BetaMessageBatchCanceledResult + | BetaMessageBatchExpiredResult; + +export interface BetaMessageBatchSucceededResult { + message: BetaMessagesAPI.BetaMessage; + + type: 'succeeded'; +} + +export interface BatchCreateParams { + /** + * Body param: List of requests for prompt completion. Each is an individual + * request to create a Message. + */ + requests: Array; + + /** + * Header param: Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export namespace BatchCreateParams { + export interface Request { + /** + * Developer-provided ID created for each request in a Message Batch. Useful for + * matching results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + custom_id: string; + + /** + * Messages API creation parameters for the individual request. + * + * See the [Messages API reference](/en/api/messages) for full documentation on + * available parameters. + */ + params: Omit; + } +} + +export interface BatchRetrieveParams { + /** + * Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export interface BatchListParams extends PageParams { + /** + * Header param: Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export interface BatchDeleteParams { + /** + * Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export interface BatchCancelParams { + /** + * Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export interface BatchResultsParams { + /** + * Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export declare namespace Batches { + export { + type BetaDeletedMessageBatch as BetaDeletedMessageBatch, + type BetaMessageBatch as BetaMessageBatch, + type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, + type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, + type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, + type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, + type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, + type BetaMessageBatchResult as BetaMessageBatchResult, + type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, + type BetaMessageBatchesPage as BetaMessageBatchesPage, + type BatchCreateParams as BatchCreateParams, + type BatchRetrieveParams as BatchRetrieveParams, + type BatchListParams as BatchListParams, + type BatchDeleteParams as BatchDeleteParams, + type BatchCancelParams as BatchCancelParams, + type BatchResultsParams as BatchResultsParams, + }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb1752308f31e493534e505ff745085107f9d210 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './messages/index'; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages/batches.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages/batches.ts new file mode 100644 index 0000000000000000000000000000000000000000..974a1be5bb223e60aded6934123c38871c28b830 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/messages/batches.ts @@ -0,0 +1,396 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as MessagesAPI from './messages'; +import { APIPromise } from '../../core/api-promise'; +import { Page, type PageParams, PagePromise } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { JSONLDecoder } from '../../internal/decoders/jsonl'; +import { AnthropicError } from '../../error'; +import { path } from '../../internal/utils/path'; + +export class Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-3-7-sonnet-20250219', + * }, + * }, + * ], + * }); + * ``` + */ + create(body: BatchCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/v1/messages/batches', { body, ...options }); + } + + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/v1/messages/batches/${messageBatchID}`, options); + } + + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list( + query: BatchListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/v1/messages/batches', Page, { query, ...options }); + } + + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/v1/messages/batches/${messageBatchID}`, options); + } + + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel`, options); + } + + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results( + messageBatchID: string, + options?: RequestOptions, + ): Promise> { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError( + `No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`, + ); + } + + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)) as APIPromise< + JSONLDecoder + >; + } +} + +export type MessageBatchesPage = Page; + +export interface DeletedMessageBatch { + /** + * ID of the Message Batch. + */ + id: string; + + /** + * Deleted object type. + * + * For Message Batches, this is always `"message_batch_deleted"`. + */ + type: 'message_batch_deleted'; +} + +export interface MessageBatch { + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + id: string; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was + * archived and its results became unavailable. + */ + archived_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which cancellation was + * initiated for the Message Batch. Specified only if cancellation was initiated. + */ + cancel_initiated_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was + * created. + */ + created_at: string; + + /** + * RFC 3339 datetime string representing the time at which processing for the + * Message Batch ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, + * errored, canceled, or expired. + */ + ended_at: string | null; + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will + * expire and end processing, which is 24 hours after creation. + */ + expires_at: string; + + /** + * Processing status of the Message Batch. + */ + processing_status: 'in_progress' | 'canceling' | 'ended'; + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once + * processing of the entire batch ends. The sum of all values always matches the + * total number of requests in the batch. + */ + request_counts: MessageBatchRequestCounts; + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. + * Specified only once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use + * the `custom_id` field to match results to requests. + */ + results_url: string | null; + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + type: 'message_batch'; +} + +export interface MessageBatchCanceledResult { + type: 'canceled'; +} + +export interface MessageBatchErroredResult { + error: Shared.ErrorResponse; + + type: 'errored'; +} + +export interface MessageBatchExpiredResult { + type: 'expired'; +} + +/** + * This is a single line in the response `.jsonl` file and does not represent the + * response as a whole. + */ +export interface MessageBatchIndividualResponse { + /** + * Developer-provided ID created for each request in a Message Batch. Useful for + * matching results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + custom_id: string; + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if + * processing failed, or the reason why processing was not attempted, such as + * cancellation or expiration. + */ + result: MessageBatchResult; +} + +export interface MessageBatchRequestCounts { + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + canceled: number; + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + errored: number; + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + expired: number; + + /** + * Number of requests in the Message Batch that are processing. + */ + processing: number; + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + succeeded: number; +} + +/** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if + * processing failed, or the reason why processing was not attempted, such as + * cancellation or expiration. + */ +export type MessageBatchResult = + | MessageBatchSucceededResult + | MessageBatchErroredResult + | MessageBatchCanceledResult + | MessageBatchExpiredResult; + +export interface MessageBatchSucceededResult { + message: MessagesAPI.Message; + + type: 'succeeded'; +} + +export interface BatchCreateParams { + /** + * List of requests for prompt completion. Each is an individual request to create + * a Message. + */ + requests: Array; +} + +export namespace BatchCreateParams { + export interface Request { + /** + * Developer-provided ID created for each request in a Message Batch. Useful for + * matching results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + custom_id: string; + + /** + * Messages API creation parameters for the individual request. + * + * See the [Messages API reference](/en/api/messages) for full documentation on + * available parameters. + */ + params: MessagesAPI.MessageCreateParamsNonStreaming; + } +} + +export interface BatchListParams extends PageParams {} + +export declare namespace Batches { + export { + type DeletedMessageBatch as DeletedMessageBatch, + type MessageBatch as MessageBatch, + type MessageBatchCanceledResult as MessageBatchCanceledResult, + type MessageBatchErroredResult as MessageBatchErroredResult, + type MessageBatchExpiredResult as MessageBatchExpiredResult, + type MessageBatchIndividualResponse as MessageBatchIndividualResponse, + type MessageBatchRequestCounts as MessageBatchRequestCounts, + type MessageBatchResult as MessageBatchResult, + type MessageBatchSucceededResult as MessageBatchSucceededResult, + type MessageBatchesPage as MessageBatchesPage, + type BatchCreateParams as BatchCreateParams, + type BatchListParams as BatchListParams, + }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/models.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/models.ts new file mode 100644 index 0000000000000000000000000000000000000000..b42ae35519cf404fbddbd35733928f1744644e0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@anthropic-ai/sdk/src/resources/models.ts @@ -0,0 +1,103 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import * as BetaAPI from './beta/beta'; +import { APIPromise } from '../core/api-promise'; +import { Page, type PageParams, PagePromise } from '../core/pagination'; +import { buildHeaders } from '../internal/headers'; +import { RequestOptions } from '../internal/request-options'; +import { path } from '../internal/utils/path'; + +export class Models extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve( + modelID: string, + params: ModelRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + const { betas } = params ?? {}; + return this._client.get(path`/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list( + params: ModelListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models', Page, { + query, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} + +export type ModelInfosPage = Page; + +export interface ModelInfo { + /** + * Unique model identifier. + */ + id: string; + + /** + * RFC 3339 datetime string representing the time at which the model was released. + * May be set to an epoch value if the release date is unknown. + */ + created_at: string; + + /** + * A human-readable name for the model. + */ + display_name: string; + + /** + * Object type. + * + * For Models, this is always `"model"`. + */ + type: 'model'; +} + +export interface ModelRetrieveParams { + /** + * Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export interface ModelListParams extends PageParams { + /** + * Header param: Optional header to specify the beta version(s) you want to use. + */ + betas?: Array; +} + +export declare namespace Models { + export { + type ModelInfo as ModelInfo, + type ModelInfosPage as ModelInfosPage, + type ModelRetrieveParams as ModelRetrieveParams, + type ModelListParams as ModelListParams, + }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..769469b2ab26d4ee6ed08df8d5747abff384b43f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml @@ -0,0 +1,8 @@ +comment: | + Hello! Thank you for contributing! + It appears that you have changed the code, but the tests that verify your change are missing. Could you please add them? +fileExtensions: + - '.ts' + - '.js' + +testDir: 'test' \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..d373acea174e183db5e10e28adc2e84026a7e6a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +env: + TZ: 'UTC' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + lint: true + license-check: true diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc new file mode 100644 index 0000000000000000000000000000000000000000..7695d35cfa1d0e719b5f816000e440366f4c2f78 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/.taprc @@ -0,0 +1,2 @@ +files: + - test/**/*.test.js \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js new file mode 100644 index 0000000000000000000000000000000000000000..57c1fd8bb5fa2bfe988efdb66343fbadcad74fda --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js @@ -0,0 +1,14 @@ +'use strict' + +const fastUri = require('fast-uri') + +module.exports = Object.freeze({ + coerceTypes: 'array', + useDefaults: true, + removeAdditional: true, + uriResolver: fastUri, + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..890d004122513abced6b3a10a8ff551b3fbc6a03 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js @@ -0,0 +1,58 @@ +'use strict' + +const Ajv = require('ajv').default +const AjvJTD = require('ajv/dist/jtd') + +const defaultAjvOptions = require('./default-ajv-options') + +class ValidatorCompiler { + constructor (externalSchemas, options) { + // This instance of Ajv is private + // it should not be customized or used + if (options.mode === 'JTD') { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions)) + } else { + this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions)) + } + + let addFormatPlugin = true + if (options.plugins && options.plugins.length > 0) { + for (const plugin of options.plugins) { + if (Array.isArray(plugin)) { + addFormatPlugin = addFormatPlugin && plugin[0].name !== 'formatsPlugin' + plugin[0](this.ajv, plugin[1]) + } else { + addFormatPlugin = addFormatPlugin && plugin.name !== 'formatsPlugin' + plugin(this.ajv) + } + } + } + + if (addFormatPlugin) { + require('ajv-formats')(this.ajv) + } + + options.onCreate?.(this.ajv) + + const sourceSchemas = Object.values(externalSchemas) + for (const extSchema of sourceSchemas) { + this.ajv.addSchema(extSchema) + } + } + + buildValidatorFunction ({ schema/*, method, url, httpPart */ }) { + // Ajv does not support compiling two schemas with the same + // id inside the same instance. Therefore if we have already + // compiled the schema with the given id, we just return it. + if (schema.$id) { + const stored = this.ajv.getSchema(schema.$id) + if (stored) { + return stored + } + } + + return this.ajv.compile(schema) + } +} + +module.exports = ValidatorCompiler diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1427ce81877b16d7407d91ac4c5f40d2e02868 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js @@ -0,0 +1,307 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const sym = Symbol.for('fastify.ajv-compiler.reference') + +const sampleSchema = Object.freeze({ + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } +}) + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + $id: 'foo', + type: 'object', + properties: { + name: { type: 'string' } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +const fastifyJtdDefault = Object.freeze({ + customOptions: { }, + mode: 'JTD' +}) + +const fastifyAjvOptionsCustom = Object.freeze({ + customOptions: { + allErrors: true, + removeAdditional: false + }, + plugins: [ + require('ajv-formats'), + [require('ajv-errors'), { singleError: false }] + ] +}) + +t.test('basic usage', t => { + t.plan(1) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ schema: sampleSchema }) + const result = validatorFunc({ name: 'hello' }) + t.equal(result, true) +}) + +t.test('array coercion', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + + const arraySchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'array', items: { type: 'string' } } + } + } + + const validatorFunc = compiler({ schema: arraySchema }) + + const inputObj = { name: 'hello' } + t.equal(validatorFunc(inputObj), true) + t.same(inputObj, { name: ['hello'] }, 'the name property should be coerced to an array') +}) + +t.test('nullable default', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory({}, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + nullable: { type: 'string', nullable: true }, + notNullable: { type: 'string' } + } + } + }) + const input = { nullable: null, notNullable: null } + const result = validatorFunc(input) + t.equal(result, true) + t.same(input, { nullable: null, notNullable: '' }, 'the notNullable field has been coerced') +}) + +t.test('plugin loading', t => { + t.plan(3) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsCustom) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + q: { + type: 'string', + format: 'date', + formatMinimum: '2016-02-06', + formatExclusiveMaximum: '2016-12-27' + } + }, + required: ['q'], + errorMessage: 'hello world' + } + }) + const result = validatorFunc({ q: '2016-10-02' }) + t.equal(result, true) + + const resultFail = validatorFunc({}) + t.equal(resultFail, false) + t.equal(validatorFunc.errors[0].message, 'hello world') +}) + +t.test('optimization - cache ajv instance', t => { + t.plan(5) + const factory = AjvCompiler() + const compiler1 = factory(externalSchemas1, fastifyAjvOptionsDefault) + const compiler2 = factory(externalSchemas1, fastifyAjvOptionsDefault) + t.equal(compiler1, compiler2, 'same instance') + t.same(compiler1, compiler2, 'same instance') + + const compiler3 = factory(externalSchemas2, fastifyAjvOptionsDefault) + t.not(compiler3, compiler1, 'new ajv instance when externa schema change') + + const compiler4 = factory(externalSchemas1, fastifyAjvOptionsCustom) + t.not(compiler4, compiler1, 'new ajv instance when externa schema change') + t.not(compiler4, compiler3, 'new ajv instance when externa schema change') +}) + +t.test('the onCreate callback can enhance the ajv instance', t => { + t.plan(2) + const factory = AjvCompiler() + + const fastifyAjvCustomOptionsFormats = Object.freeze({ + onCreate (ajv) { + for (const [formatName, format] of Object.entries(this.customOptions.formats)) { + ajv.addFormat(formatName, format) + } + }, + customOptions: { + formats: { + date: /foo/ + } + } + }) + + const compiler1 = factory(externalSchemas1, fastifyAjvCustomOptionsFormats) + const validatorFunc = compiler1({ + schema: { + type: 'string', + format: 'date' + } + }) + const result = validatorFunc('foo') + t.equal(result, true) + + const resultFail = validatorFunc('2016-10-02') + t.equal(resultFail, false) +}) + +// https://github.com/fastify/fastify/pull/2969 +t.test('compile same $id when in external schema', t => { + t.plan(3) + const factory = AjvCompiler() + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const compiler = factory({ + [base.$id]: base, + [refSchema.$id]: refSchema + + }, fastifyAjvOptionsDefault) + + t.notOk(compiler[sym], 'the ajv reference do not exists if code is not activated') + + const validatorFunc1 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + const validatorFunc2 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + t.pass('the compile does not fail if the schema compiled is already in the external schemas') + t.equal(validatorFunc1, validatorFunc2, 'the returned function is the same') +}) + +t.test('JTD MODE', t => { + t.plan(2) + + t.test('compile jtd schema', t => { + t.plan(4) + const factory = AjvCompiler() + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, fastifyJtdDefault) + const validatorFunc = compiler({ schema: jtdSchema }) + t.pass('generated validation function for JTD SCHEMA') + + const result = validatorFunc({ + version: '2', + foo: [] + }) + t.notOk(result, 'failed validation') + t.type(validatorFunc.errors, 'Array') + + const success = validatorFunc({ + version: '1', + foo: 42 + }) + t.ok(success) + }) + + t.test('fastify integration', async t => { + const factory = AjvCompiler() + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.post('/', { + schema: { + body: { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + } + }, () => {}) + + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'this is not a number' + } + }) + + t.equal(res.statusCode, 400) + t.equal(res.json().message, 'body/foo must be uint8') + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dacb0e893676ac713f48381cebfd380a3b1d3ef4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js @@ -0,0 +1,264 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const ajvFormats = require('ajv-formats') +const ajvErrors = require('ajv-errors') +const localize = require('ajv-i18n') + +t.test('Format Baseline test', async (t) => { + const app = buildApplication({ + customOptions: { + validateFormats: false + } + }) + + const res = await app.inject({ + url: '/hello', + headers: { + 'x-foo': 'hello', + 'x-date': 'not a date', + 'x-email': 'not an email' + }, + query: { + foo: 'hello', + date: 'not a date', + email: 'not an email' + } + }) + t.equal(res.statusCode, 200, 'format validation does not apply as configured') + t.equal(res.payload, 'hello') +}) + +t.test('Custom Format plugin loading test', (t) => { + t.plan(6) + const app = buildApplication({ + customOptions: { + validateFormats: true + }, + plugins: [[ajvFormats, { mode: 'fast' }]] + }) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Format plugin set by default test', (t) => { + t.plan(6) + const app = buildApplication({}) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Custom error messages', (t) => { + t.plan(9) + + const app = buildApplication({ + customOptions: { + removeAdditional: false, + allErrors: true + }, + plugins: [ajvFormats, ajvErrors] + }) + + const errorMessage = { + required: 'custom miss', + type: 'custom type', // will not replace internal "type" error for the property "foo" + _: 'custom type', // this prop will do it + additionalProperties: 'custom too many params' + } + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + }, + additionalProperties: false, + errorMessage + } + } + }) + + app.inject({ + url: '/', + method: 'post', + payload: {} + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.required) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 'not a number' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.type) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 3, bar: 'ops' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.additionalProperties) + }) +}) + +t.test('Custom i18n error messages', (t) => { + t.plan(3) + + const app = buildApplication({ + customOptions: { + allErrors: true, + messages: false + }, + plugins: [ajvFormats] + }) + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + } + } + } + }) + + app.setErrorHandler((error, request, reply) => { + t.pass('Error handler executed') + if (error.validation) { + localize.ru(error.validation) + reply.status(400).send(error.validation) + return + } + t.fail('not other errors') + }) + + app.inject({ + method: 'POST', + url: '/', + payload: { + foo: 'string' + } + }, (err, res) => { + t.error(err) + t.equal(res.json()[0].message, 'должно быть integer') + }) +}) + +function buildApplication (ajvOptions) { + const factory = AjvCompiler() + + const app = fastify({ + ajv: ajvOptions, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.get('/:id', { + schema: { + headers: { + type: 'object', + required: [ + 'x-foo', + 'x-date', + 'x-email' + ], + properties: { + 'x-foo': { type: 'string' }, + 'x-date': { type: 'string', format: 'date-time' }, + 'x-email': { type: 'string', format: 'email' } + } + }, + query: { + type: 'object', + required: [ + 'foo', + 'date', + 'email' + ], + properties: { + foo: { type: 'string' }, + date: { type: 'string', format: 'date-time' }, + email: { type: 'string', format: 'email' } + } + }, + params: { + type: 'object', + properties: { + id: { type: 'string', format: 'uuid' } + } + } + } + }, async () => 'hello') + + return app +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20821e0d1fc1a4849b9d0dfae98d7f38f8f81cdd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js @@ -0,0 +1,279 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } +} + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +t.test('basic serializer usage', t => { + t.plan(4) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ schema: jtdSchema }) + t.equal(serializeFunc({ version: '1', foo: 42 }), '{"version":"1","foo":42}') + t.equal(serializeFunc({ version: '2', foo: 'hello' }), '{"version":"2","foo":"hello"}') + t.equal(serializeFunc({ version: '3', foo: 'hello' }), '{"version":"3"}') + t.equal(serializeFunc({ version: '2', foo: ['not', 1, { string: 'string' }] }), '{"version":"2","foo":"not,1,[object Object]"}') +}) + +t.test('external schemas are ignored', t => { + t.plan(1) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas2, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ + schema: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + }, + properties: { + userLoc: { ref: 'coordinates' }, + serverLoc: { ref: 'coordinates' } + } + } + }) + t.equal(serializeFunc( + { userLoc: { lat: 50, lng: -90 }, serverLoc: { lat: -15, lng: 50 } }), + '{"userLoc":{"lat":50,"lng":-90},"serverLoc":{"lat":-15,"lng":50}}' + ) +}) + +t.test('fastify integration within JTD serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration and cached serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.register(async function plugin (app, opts) { + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + }) + + app.register(async function plugin (app, opts) { + app.post('/two', { + schema: { + body: jtdSchema, + response: { + 400: jtdSchema + } + } + }, () => {}) + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration within JTD serializer and custom options', async t => { + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + serializerOpts: { + allErrors: true, + logger: 'wrong-value' + }, + schemaController: { + compilersFactory: { + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + response: { + 200: { + properties: { + test: { type: 'boolean' } + } + } + } + } + }, async () => { }) + + try { + await app.ready() + t.fail('should throw') + } catch (error) { + t.equal(error.message, 'logger must implement log, warn and error methods', 'the wrong setting is forwarded to ajv/jtd') + } +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..391e7b7ad24d9e16f0218d599df6abb87d521d38 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts @@ -0,0 +1,226 @@ +import { AnySchemaObject, ValidateFunction } from 'ajv' +import { AnyValidateFunction } from 'ajv/dist/core' +import { expectAssignable, expectType } from 'tsd' +import AjvCompiler, { AjvReference, ValidatorFactory, StandaloneValidator, RouteDefinition, ErrorObject, BuildCompilerFromPool, BuildSerializerFromPool, ValidatorCompiler } from '..' + +{ + const compiler = AjvCompiler({}) + expectType(compiler) +} +{ + const compiler = AjvCompiler() + expectType(compiler) +} +{ + const compiler = AjvCompiler({ jtdSerializer: false }) + expectType(compiler) +} + +{ + const factory = AjvCompiler({ jtdSerializer: false }) + expectType(factory) + factory({}, { + onCreate (ajv) { + expectType(ajv) + } + }) +} + +{ + const compiler = AjvCompiler({ jtdSerializer: true }) + expectType(compiler) +} +const reader = StandaloneValidator({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as ValidateFunction + }, +}) +expectAssignable(reader) + +const writer = StandaloneValidator({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectAssignable(writer) + +expectType(({} as ErrorObject).data) +expectType(({} as ErrorObject).instancePath) +expectType(({} as ErrorObject).keyword) +expectType(({} as ErrorObject).message) +expectType>(({} as ErrorObject).params) +expectType(({} as ErrorObject).parentSchema) +expectType(({} as ErrorObject).propertyName) +expectType(({} as ErrorObject).schema) +expectType(({} as ErrorObject).schemaPath) + +expectType(AjvReference) + +{ + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const externalSchemas1 = { + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } + } + + const factory = AjvCompiler({ jtdSerializer: true }) + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectAssignable(compiler) + const serializeFunc = compiler({ schema: jtdSchema }) + expectType<(data: unknown) => string>(serializeFunc) + expectType(serializeFunc({ version: '1', foo: 42 })) +} +// JTD +{ + const factory = AjvCompiler() + expectType(factory) + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, { + customOptions: {}, + mode: 'JTD' + }) + expectAssignable(compiler) + const validatorFunc = compiler({ schema: jtdSchema }) + expectAssignable(validatorFunc) + + expectType>(validatorFunc({ + version: '2', + foo: [] + })) +} + +// generate standalone code +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = StandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + expectType(routeOpts) + expectType(schemaValidationCode) + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectAssignable(compiler(endpointSchema)) +} + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + const factory = StandaloneValidator({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as ValidateFunction + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectType>(compiler(endpointSchema)) +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.editorconfig b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..db87e1fb3f74f240d34c36c112c06adae84792eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = false +insert_final_newline = false \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.gitattributes b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..cad1c32e3deb59f649a90fb55994a7c6a0685f64 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.gitattributes @@ -0,0 +1,5 @@ +# Set the default behavior, in case people don't have core.autocrlf set +* text=auto + +# Require Unix line endings +* text eol=lf diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.github/stale.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/bench.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/bench.js new file mode 100644 index 0000000000000000000000000000000000000000..30dd09a26e956a65601ccc7465a8d396e02600d2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/bench.js @@ -0,0 +1,17 @@ +'use strict' + +const fastify = require('fastify')() + +fastify.register((instance, _opts, next) => { + instance.register(require('./index')) + instance.get('/fastify', (_req, reply) => reply.send('ok')) + next() +}) + +fastify.register((instance, _opts, next) => { + instance.use(require('cors')()) + instance.get('/express', (_req, reply) => reply.send('ok')) + next() +}) + +fastify.listen({ port: 3000 }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/package.json new file mode 100644 index 0000000000000000000000000000000000000000..15818d33bebbacf3a87f948d0af6227164af467e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/package.json @@ -0,0 +1,15 @@ +{ + "name": "benchmark", + "version": "1.0.0", + "description": "", + "main": "vary.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "benchmark": "^2.1.4", + "vary": "^1.1.2" + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js new file mode 100644 index 0000000000000000000000000000000000000000..4aca63d803c065af6efd9464865bad42696eac1d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js @@ -0,0 +1,34 @@ +'use strict' + +const benchmark = require('benchmark') +const vary = require('vary') +const createAddFieldnameToVary = require('../vary').createAddFieldnameToVary + +const replyMock = (header) => ({ + getHeader () { return header }, + setHeader () { }, + header () { } +}) + +const addAcceptToVary = createAddFieldnameToVary('Accept') +const addWildcardToVary = createAddFieldnameToVary('*') +const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') +const addXFooToVary = createAddFieldnameToVary('X-Foo') + +new benchmark.Suite() + .add('vary - field to undefined', function () { vary(replyMock(undefined), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - field to *', function () { vary(replyMock('*'), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - * to field', function () { vary(replyMock('Accept-Encoding'), '*') }, { minSamples: 100 }) + .add('vary - field to empty', function () { vary(replyMock(''), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - fields string to empty', function () { vary(replyMock(''), 'Accept') }, { minSamples: 100 }) + .add('vary - field to fields', function () { vary(replyMock('Accept, Accept-Encoding, Accept-Language'), 'X-Foo') }, { minSamples: 100 }) + + .add('cors - field to undefined', function () { addAcceptEncodingToVary(replyMock(undefined)) }, { minSamples: 100 }) + .add('cors - field to *', function () { addAcceptEncodingToVary(replyMock('*')) }, { minSamples: 100 }) + .add('cors - * to field', function () { addWildcardToVary(replyMock('Accept-Encoding')) }, { minSamples: 100 }) + .add('cors - field to empty', function () { addAcceptEncodingToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - fields string to empty', function () { addAcceptToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - field to fields', function () { addXFooToVary(replyMock('Accept, Accept-Encoding, Accept-Language')) }, { minSamples: 100 }) + + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/cors.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/cors.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d64c48acfc672acd147640e931c41a3fee7219bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/cors.test.js @@ -0,0 +1,1052 @@ +'use strict' + +const { test } = require('node:test') +const { createReadStream, statSync, readFileSync } = require('node:fs') +const Fastify = require('fastify') +const cors = require('../') +const { resolve } = require('node:path') +const { setTimeout: sleep } = require('node:timers/promises') + +test('Should add cors headers', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should add cors headers when payload is a stream', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + const filePath = resolve(__dirname, __filename) + + fastify.get('/', (_req, reply) => { + const stream = createReadStream(filePath) + reply + .type('application/json') + .header('Content-Length', statSync(filePath).size) + .send(stream) + }) + + const fileContent = readFileSync(filePath, 'utf-8') + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, fileContent) + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'content-length': res.headers['content-length'] + + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'content-length': statSync(filePath).size.toString() + }) +}) + +test('Should add cors headers (custom values)', async t => { + t.plan(10) + + const fastify = Fastify() + fastify.register(cors, { + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 321 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, woo', + 'access-control-max-age': '123', + 'cache-control': 'max-age=321', + 'content-length': '0' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Should support dynamic config (callback)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: '456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req, cb) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + + const config = configs[requestId] + requestId++ + if (config) { + cb(null, config) + } else { + cb(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': '456', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config (Promise)', async t => { + t.plan(23) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: true // Invalid value should be ignored + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: 'public, max-age=456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'sample.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const acutalHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(acutalHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + t.assert.strictEqual(res.headers['cache-control'], undefined, 'cache-control omitted (invalid value)') + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders3 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders3, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': 'public, max-age=456', // cache-control included (custom string) + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config. (Invalid function)', async t => { + t.plan(2) + + const fastify = Fastify() + fastify.register(cors, () => () => {}) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin)', async t => { + t.plan(6) + + const fastify = Fastify() + const origin = function (header, cb) { + t.assert.strictEqual(header, 'example.com') + t.assert.equal(this, fastify) + cb(null, true) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, false) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(new Error('ouch')) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (invalid result)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, undefined) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(true) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(false) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored - promises)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((_resolve, reject) => { + t.assert.strictEqual(header, 'example.com') + reject(new Error('ouch')) + }) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should reply 404 without cors headers when origin is false', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + origin: false, + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.payload, '{"message":"Route OPTIONS:/ not found","error":"Not Found","statusCode":404}') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '76', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Server error if origin option is falsy but not false', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '' }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.deepStrictEqual(res.json(), { statusCode: 500, error: 'Internal Server Error', message: 'Invalid CORS origin option' }) + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Allow only request from a specific origin', async t => { + t.plan(5) + + const fastify = Fastify() + fastify.register(cors, { origin: 'other.io' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + 'other.io' + ) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Allow only request from multiple specific origin', async t => { + t.plan(9) + + const fastify = Fastify() + fastify.register(cors, { origin: ['other.io', 'example.com'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'other.io' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'other.io', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'foo.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers.vary, + 'Origin' + ) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) + +test('Allow only request from a specific origin using regex', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { origin: /(?:example|other)\.com\/?$/giu }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // .test was previously used, which caused 2 consecutive requests to return + // different results with global (e.g. /g) regexes. Therefore, check this + // twice to check consistency + for (let i = 0; i < 2; i++) { + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'https://www.example.com/' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'https://www.example.com/', + vary: 'Origin' + }) + } +}) + +test('Disable preflight', async t => { + t.plan(7) + + const fastify = Fastify() + fastify.register(cors, { preflight: false }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin', async t => { + t.plan(12) + + const fastify = Fastify() + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // Invalid Preflight + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) + + // Valid Preflight + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + t.assert.strictEqual(res.headers.vary, + 'Origin, Access-Control-Request-Headers' + ) + + // Other Route + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin (vary is array)', async t => { + t.plan(4) + + const fastify = Fastify() + + // Mock getHeader function + fastify.decorateReply('getHeader', () => ['foo', 'bar']) + + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'foo, bar, Origin' + ) +}) + +test('Allow only request from with specific headers', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + allowedHeaders: 'foo', + exposedHeaders: 'bar' + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.deepStrictEqual(res.headers['access-control-allow-headers'], + 'foo' + ) + t.assert.notDeepEqual(res.headers.vary, 'Origin') + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-expose-headers'], + 'bar' + ) +}) + +test('Should support wildcard config /1', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should support wildcard config /2', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: ['*'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should allow routes to disable CORS individually', async t => { + t.plan(6) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/cors-enabled', (_req, reply) => { + reply.send('ok') + }) + + fastify.get('/cors-disabled', { config: { cors: false } }, (_req, reply) => { + reply.send('ok') + }) + + // Test CORS enabled route + let res = await fastify.inject({ + method: 'GET', + url: '/cors-enabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') + + // Test CORS disabled route + res = await fastify.inject({ + method: 'GET', + url: '/cors-disabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/vary.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/vary.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4357add02a890853b0183e6b54bdf15cda561f86 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/test/vary.test.js @@ -0,0 +1,237 @@ +'use strict' + +const { test } = require('node:test') +const { createAddFieldnameToVary } = require('../vary') +const { parse } = require('../vary') + +test('Should set * even if we set a specific field', async t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return '*' + }, + header () { + t.fail('Should not be here') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set * even if we set a specific field', t => { + t.plan(2) + + const addWildcardToVary = createAddFieldnameToVary('*') + const replyMock = { + getHeader () { + return 'Origin' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addWildcardToVary(replyMock) +}) + +test('Should set * when field contains a *', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ['Origin', '*', 'Access-Control-Request-Headers'] + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Access-Control-Request-Headers' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Access-Control-Request-Headers, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring consecutive commas', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring whitespace', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers ,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers ,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set the field as value for vary if no vary is defined', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return undefined + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Origin') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set * as value for vary if vary contains *', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Accept,*' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set Accept-Encoding as value for vary if vary is empty string', t => { + t.plan(2) + + const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') + const replyMock = { + getHeader () { + return '' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding') + } + } + + addAcceptEncodingToVary(replyMock) +}) + +test('Should have no issues with values containing dashes', t => { + t.plan(2) + + const addXFooToVary = createAddFieldnameToVary('X-Foo') + const replyMock = { + value: 'Accept-Encoding', + getHeader () { + return this.value + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding, X-Foo') + this.value = value + } + } + + addXFooToVary(replyMock) + addXFooToVary(replyMock) +}) + +test('Should ignore the header as value for vary if it is already in vary', t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Origin' + }, + header () { + t.fail('Should not be here') + } + } + addOriginToVary(replyMock) + addOriginToVary(replyMock) + + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('parse', t => { + t.plan(18) + t.assert.deepStrictEqual(parse(''), []) + t.assert.deepStrictEqual(parse('a'), ['a']) + t.assert.deepStrictEqual(parse('a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse(' a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b '), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c,'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c, '), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(',a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(' ,a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,,b,,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + + // one for the cache + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) +}) + +test('createAddFieldnameToVary', async t => { + t.plan(4) + t.assert.strictEqual(typeof createAddFieldnameToVary('valid-header'), 'function') + await t.assert.rejects( + async () => createAddFieldnameToVary('invalid:header'), + (err) => { + t.assert.strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.message, 'Fieldname contains invalid characters.') + return true + } + ) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/types/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eab0b1ba66177929766c574ec77c2f62e6c0cfbb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/cors/types/index.d.ts @@ -0,0 +1,126 @@ +/// + +import { FastifyInstance, FastifyPluginCallback, FastifyRequest, LogLevel } from 'fastify' + +type OriginCallback = (err: Error | null, origin: ValueOrArray) => void +type OriginType = string | boolean | RegExp +type ValueOrArray = T | ArrayOfValueOrArray + +interface ArrayOfValueOrArray extends Array> { +} + +type FastifyCorsPlugin = FastifyPluginCallback< + NonNullable | fastifyCors.FastifyCorsOptionsDelegate +> + +type FastifyCorsHook = + | 'onRequest' + | 'preParsing' + | 'preValidation' + | 'preHandler' + | 'preSerialization' + | 'onSend' + +declare namespace fastifyCors { + export type OriginFunction = (origin: string | undefined, callback: OriginCallback) => void + export type AsyncOriginFunction = (origin: string | undefined) => Promise> + + export interface FastifyCorsOptions { + /** + * Configures the Lifecycle Hook. + */ + hook?: FastifyCorsHook; + + /** + * Configures the delegate function. + */ + delegator?: FastifyCorsOptionsDelegate; + + /** + * Configures the Access-Control-Allow-Origin CORS header. + */ + origin?: ValueOrArray | fastifyCors.AsyncOriginFunction | fastifyCors.OriginFunction; + /** + * Configures the Access-Control-Allow-Credentials CORS header. + * Set to true to pass the header, otherwise it is omitted. + */ + credentials?: boolean; + /** + * Configures the Access-Control-Expose-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') + * or an array (ex: ['Content-Range', 'X-Content-Range']). + * If not specified, no custom headers are exposed. + */ + exposedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Type,Authorization') + * or an array (ex: ['Content-Type', 'Authorization']). If not + * specified, defaults to reflecting the headers specified in the + * request's Access-Control-Request-Headers header. + */ + allowedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Methods CORS header. + * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). + */ + methods?: string | string[]; + /** + * Configures the Access-Control-Max-Age CORS header. + * Set to an integer to pass the header, otherwise it is omitted. + */ + maxAge?: number; + /** + * Configures the Cache-Control header for CORS preflight responses. + * Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`, + * or set to a string to pass the header as `Cache-Control: ${cacheControl}` (fully define + * the header value), otherwise the header is omitted. + */ + cacheControl?: number | string; + /** + * Pass the CORS preflight response to the route handler (default: false). + */ + preflightContinue?: boolean; + /** + * Provides a status code to use for successful OPTIONS requests, + * since some legacy browsers (IE11, various SmartTVs) choke on 204. + */ + optionsSuccessStatus?: number; + /** + * Pass the CORS preflight response to the route handler (default: true). + */ + preflight?: boolean; + /** + * Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin). + * Preflight requests without the required headers will result in 400 errors when set to `true` (default: `true`). + */ + strictPreflight?: boolean; + /** + * Hide options route from the documentation built using fastify-swagger (default: true). + */ + hideOptionsRoute?: boolean; + + /** + * Sets the Fastify log level specifically for the internal OPTIONS route + * used to handle CORS preflight requests. For example, setting this to `'silent'` + * will prevent these requests from being logged. + * Useful for reducing noise in application logs. + * Default: inherits Fastify's global log level. + */ + logLevel?: LogLevel; + } + + export interface FastifyCorsOptionsDelegateCallback { (req: FastifyRequest, cb: (error: Error | null, corsOptions?: FastifyCorsOptions) => void): void } + export interface FastifyCorsOptionsDelegatePromise { (req: FastifyRequest): Promise } + export type FastifyCorsOptionsDelegate = FastifyCorsOptionsDelegateCallback | FastifyCorsOptionsDelegatePromise + export type FastifyPluginOptionsDelegate = (instance: FastifyInstance) => T + + export const fastifyCors: FastifyCorsPlugin + export { fastifyCors as default } +} + +declare function fastifyCors ( + ...params: Parameters +): ReturnType + +export = fastifyCors diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/create.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/create.js new file mode 100644 index 0000000000000000000000000000000000000000..bb9abbfe1b34856cb81ea8fd7157ef8726c671fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/create.js @@ -0,0 +1,9 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +new benchmark.Suite() + .add('create FastifyError', function () { createError('CODE', 'Not available') }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js new file mode 100644 index 0000000000000000000000000000000000000000..890aaf0ac18f6ba3cb75e36d58421e1ac8f84673 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js @@ -0,0 +1,18 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +const FastifyError1 = createError('CODE', 'Not %s available') +const FastifyError2 = createError('CODE', 'Not %s available %s') + +const cause = new Error('cause') +new benchmark.Suite() + .add('instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 1', function () { new FastifyError1('q') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 2', function () { new FastifyError2('qq', 'ss') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError cause', function () { new FastifyError2({ cause }) }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js new file mode 100644 index 0000000000000000000000000000000000000000..b626b5c79da786de28356722976d5ed3af0fe958 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +Error.stackTraceLimit = 0 + +new benchmark.Suite() + .add('no-stack instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('no-stack instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js new file mode 100644 index 0000000000000000000000000000000000000000..119154925ed8f6072c5f670c95ced9a52ca395f7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js @@ -0,0 +1,11 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') + +new benchmark.Suite() + .add('FastifyError toString', function () { new FastifyError().toString() }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js new file mode 100644 index 0000000000000000000000000000000000000000..34d56fbf92cc1fcb391d8abdb2a543d4f09d0afa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js @@ -0,0 +1,263 @@ +'use strict' + +const cp = require('node:child_process') +const fs = require('node:fs') +const path = require('node:path') +const os = require('node:os') +const test = require('node:test') +const { createError, FastifyError } = require('..') + +test('Readme: All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: All instantiated errors will be instances of the `FastifyError` class. The `FastifyError` class can be required from the module directly.', (t) => { + t.plan(1) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof FastifyError) +}) + +test('Readme: It is possible to create a `FastifyError` that extends another `FastifyError`, created by `createError`, while instanceof working correctly.', (t) => { + t.plan(5) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new ChildCustomError('world') + + t.assert.ok(customError instanceof ChildCustomError) + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof FastifyError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: Changing the code of an instantiated Error will not change the result of the `instanceof` operator.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new CustomError('world') + customError.code = 'ANOTHER_ERROR_CODE' + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof AnotherCustomError === false) + t.assert.ok(customError instanceof FastifyError) +}) + +test('check if createError creates an Error which is instanceof Error', (t) => { + t.plan(3) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error which is instanceof FastifyError', (t) => { + t.plan(4) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error with the right BaseConstructor', (t) => { + t.plan(2) + + const CustomFastifyError = createError('CODE', 'Not available', 500, TypeError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) +}) + +test('check if createError creates an Error with the right BaseConstructor, which is a FastifyError', (t) => { + t.plan(6) + + const BaseFastifyError = createError('CODE', 'Not available', 500, TypeError) + const CustomFastifyError = createError('CODE', 'Not available', 500, BaseFastifyError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof BaseFastifyError) + t.assert.ok(err instanceof CustomFastifyError) + t.assert.ok(err instanceof SyntaxError === false) +}) + +// for more information see https://github.com/fastify/fastify-error/pull/86#issuecomment-1301466407 +test('ensure that instanceof works accross different installations of the fastify-error module', async (t) => { + const assertsPlanned = 5 + t.plan(assertsPlanned) + + // We need to create a test environment where fastify-error is installed in two different locations + // and then we will check if the error created in one location is instanceof the error created in the other location + // This is done by creating a test directory with the following structure: + + // / + // ├── index.js + // └── node_modules/ + // ├── fastify-error/ + // │ └── index.js + // └── dep/ + // ├── index.js + // └── node_modules/ + // └── fastify-error/ + // └── index.js + + const testDirectoryPrefix = 'fastify-error-instanceof-test-' + + const testCwd = path.resolve(os.tmpdir(), `${testDirectoryPrefix}${Math.random().toString(36).substring(2, 15)}`) + fs.mkdirSync(testCwd, { recursive: true }) + + // Create the index.js. It will be executed as a forked process, so we need to + // use process.send to send messages back to the parent process. + fs.writeFileSync(path.resolve(testCwd, 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError, FastifyError } = require('fastify-error') + const { foo } = require('dep') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of the test-project') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + const NotChildBoom = createError('NotChildBoom', 'NotChildBoom', 500, Boom) + + try { + foo() + } catch (err) { + process.send(err instanceof Error) + process.send(err instanceof FastifyError) + process.send(err instanceof NotChildBoom) + process.send(err instanceof Boom) + process.send(err instanceof ChildBoom) + } + `) + + // Create /node_modules/fastify-error directory + // Copy the index.js file to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/node_modules/fastify-error directory + // Copy the index.js to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/index.js. It will export a function foo which will + // throw an error when called. The error will be an instance of ChildBoom, created + // by the fastify-error module in the node_modules directory of dep. + fs.writeFileSync(path.resolve(testCwd, 'node_modules', 'dep', 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError } = require('fastify-error') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of dep') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + + module.exports.foo = function foo () { + throw new ChildBoom('foo go Boom') + } + `) + + const finishedPromise = { + promise: undefined, + reject: undefined, + resolve: undefined, + } + + finishedPromise.promise = new Promise((resolve, reject) => { + finishedPromise.resolve = resolve + finishedPromise.reject = reject + }) + + const child = cp.fork(path.resolve(testCwd, 'index.js'), { + cwd: testCwd, + stdio: 'inherit', + env: { + ...process.env, + NODE_OPTIONS: '--no-warnings' + }, + }) + + let messageCount = 0 + child.on('message', message => { + try { + switch (messageCount) { + case 0: + t.assert.strictEqual(message, true, 'instanceof Error') + break + case 1: + t.assert.strictEqual(message, true, 'instanceof FastifyError') + break + case 2: + t.assert.strictEqual(message, false, 'instanceof NotChildBoom') + break + case 3: + t.assert.strictEqual(message, true, 'instanceof Boom') + break + case 4: + t.assert.strictEqual(message, true, 'instanceof ChildBoom') + break + } + if (++messageCount === assertsPlanned) { + finishedPromise.resolve() + } + } catch (err) { + finishedPromise.reject(err) + } + }) + + child.on('error', err => { + finishedPromise.reject(err) + }) + + await finishedPromise.promise + + // Cleanup + // As we are creating the test-setup on the fly in the /tmp directory, we can remove it + // safely when we are done. It is not relevant for the test if the deletion fails. + try { + fs.rmSync(testCwd, { recursive: true, force: true }) + } catch {} +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e59d9febe28d1cad109f914d95c02551097ec59 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.d.ts @@ -0,0 +1,49 @@ +declare function createError ( + code: C, + message: string, + statusCode: SC, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C, statusCode: SC }, Arg> + +declare function createError ( + code: C, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C }, Arg> + +declare function createError ( + code: string, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: string }, Arg> + +type CreateError = typeof createError + +declare namespace createError { + export interface FastifyError extends Error { + code: string + name: string + statusCode?: number + } + + export interface FastifyErrorConstructor< + E extends { code: string, statusCode?: number } = { code: string, statusCode?: number }, + T extends unknown[] = [any?, any?, any?] + > { + new(...arg: T): FastifyError & E + (...arg: T): FastifyError & E + readonly prototype: FastifyError & E + } + + export const FastifyError: FastifyErrorConstructor + + export const createError: CreateError + export { createError as default } +} + +export = createError diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a4398d4a452995bea323b67f7f2b041a6332af3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts @@ -0,0 +1,92 @@ +import createError, { FastifyError, FastifyErrorConstructor } from '..' +import { expectType, expectError } from 'tsd' + +const CustomError = createError('ERROR_CODE', 'message') +expectType>(CustomError) +const err = new CustomError() +expectType(err) +expectType<'ERROR_CODE'>(err.code) +expectType(err.message) +expectType(err.statusCode) + +const CustomErrorNoStackTrace = createError('ERROR_CODE', 'message', undefined, undefined, false) +expectType>(CustomErrorNoStackTrace) +const errNoStackTrace = new CustomErrorNoStackTrace() +expectType(errNoStackTrace) +expectType<'ERROR_CODE'>(errNoStackTrace.code) +expectType(errNoStackTrace.message) +expectType(errNoStackTrace.statusCode) + +const CustomTypedError = createError('OTHER_CODE', 'message', 400) +expectType>(CustomTypedError) +const typed = new CustomTypedError() +expectType(typed) +expectType<'OTHER_CODE'>(typed.code) +expectType(typed.message) +expectType<400>(typed.statusCode) + +/* eslint-disable no-new */ +const CustomTypedArgError = createError<[string]>('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError('a') +expectError(CustomTypedArgError('a', 'b')) +expectError(new CustomTypedArgError('a', 'b')) +expectError(CustomTypedArgError(1)) +expectError(new CustomTypedArgError(1)) + +const CustomTypedArgError2 = createError('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError2('a') +expectError(CustomTypedArgError2('a', 'b')) +expectError(new CustomTypedArgError2('a', 'b')) +expectError(CustomTypedArgError2(1)) +expectError(new CustomTypedArgError2(1)) + +const CustomTypedArgError3 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError3('a')) +CustomTypedArgError3('a', 'b') +new CustomTypedArgError3('a', 'b') +expectError(CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1, 2)) +expectError(new CustomTypedArgError3('1', 2)) +expectError(new CustomTypedArgError3(1, '2')) + +const CustomTypedArgError4 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError4('a')) +CustomTypedArgError4('a', 'b') +new CustomTypedArgError4('a', 'b') +expectError(CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1, 2)) +expectError(new CustomTypedArgError4('1', 2)) +expectError(new CustomTypedArgError4(1, '2')) + +const CustomTypedArgError5 = createError<[string, string, string, string]>('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError5('a')) +expectError(new CustomTypedArgError5('a', 'b')) +expectError(new CustomTypedArgError5('a', 'b', 'c')) +CustomTypedArgError5('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError5('a', 'b', 'c', 'd', 'e')) + +const CustomTypedArgError6 = createError('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError6('a')) +expectError(new CustomTypedArgError6('a', 'b')) +expectError(new CustomTypedArgError6('a', 'b', 'c')) +CustomTypedArgError6('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError6('a', 'b', 'c', 'd', 'e')) + +const CustomErrorWithErrorConstructor = createError('ERROR_CODE', 'message', 500, TypeError) +expectType>(CustomErrorWithErrorConstructor) +CustomErrorWithErrorConstructor({ cause: new Error('Error') }) +const customErrorWithErrorConstructor = CustomErrorWithErrorConstructor() +if (customErrorWithErrorConstructor instanceof FastifyError) { + expectType<'ERROR_CODE'>(customErrorWithErrorConstructor.code) + expectType(customErrorWithErrorConstructor.message) + expectType<500>(customErrorWithErrorConstructor.statusCode) +} + +const error = new FastifyError('ERROR_CODE', 'message', 500) +if (error instanceof FastifyError) { + expectType(error.code) + expectType(error.message) + expectType(error.statusCode) +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..185ff2ec247992d88eb49b8581f20d8676c859f1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.eslintrc @@ -0,0 +1 @@ +{"extends": "standard"} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9323c971a1d4da1cf1b95f244fa2d3b7263673a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/index.js @@ -0,0 +1,8 @@ +'use strict' + +const { SerializerSelector, StandaloneSerializer } = require('./standalone') + +module.exports = SerializerSelector +module.exports.default = SerializerSelector +module.exports.SerializerSelector = SerializerSelector +module.exports.StandaloneSerializer = StandaloneSerializer diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cc104b7c4ff802cda367b2ed32ed9a500fc13637 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/package.json @@ -0,0 +1,71 @@ +{ + "name": "@fastify/fast-json-stringify-compiler", + "description": "Build and manage the fast-json-stringify instances for the fastify framework", + "version": "5.0.3", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "unit": "c8 --100 node --test", + "test": "npm run unit && npm run test:typescript", + "test:typescript": "tsd" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/fast-json-stringify-compiler.git" + }, + "keywords": [], + "author": "Manuel Spigolon (https://github.com/Eomm)", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "James Sumners", + "url": "https://james.sumners.info" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/fast-json-stringify-compiler/issues" + }, + "homepage": "https://github.com/fastify/fast-json-stringify-compiler#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "c8": "^10.1.3", + "eslint": "^9.17.0", + "fastify": "^5.0.0", + "neostandard": "^0.12.0", + "sanitize-filename": "^1.6.3", + "tsd": "^0.31.0" + }, + "pre-commit": [ + "lint", + "test" + ], + "dependencies": { + "fast-json-stringify": "^6.0.0" + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6ecdc1714e2e1809c6a6fee7ddb1d3b0feab5cc2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js @@ -0,0 +1,230 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') +const fastify = require('fastify') +const sanitize = require('sanitize-filename') + +const { StandaloneSerializer: FjsStandaloneCompiler } = require('../') + +const generatedFileNames = [] + +function generateFileName (routeOpts) { + const fileName = `/fjs-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` + generatedFileNames.push(fileName) + return fileName +} + +test('standalone', async t => { + t.plan(5) + + t.after(async () => { + for (const fileName of generatedFileNames) { + try { + await fs.promises.unlink(path.join(__dirname, fileName)) + } catch {} + } + }) + + t.test('errors', t => { + t.plan(2) + t.assert.throws(() => { + FjsStandaloneCompiler() + }, 'missing restoreFunction') + t.assert.throws(() => { + FjsStandaloneCompiler({ readMode: false }) + }, 'missing storeFunction') + }) + + t.test('generate standalone code', t => { + t.plan(5) + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + t.assert.deepStrictEqual(routeOpts, endpointSchema) + t.assert.ok(typeof schemaSerializerCode === 'string') + fs.writeFileSync(path.join(__dirname, '/fjs-generated.js'), schemaSerializerCode) + generatedFileNames.push('/fjs-generated.js') + t.assert.ok('stored the serializer function') + } + }) + + const compiler = factory(schemaMap) + compiler(endpointSchema) + t.assert.ok('compiled the endpoint schema') + + t.test('usage standalone code', t => { + t.plan(3) + const standaloneSerializer = require('./fjs-generated') + t.assert.ok(standaloneSerializer) + + const valid = standaloneSerializer({ hello: 'world' }) + t.assert.deepStrictEqual(valid, JSON.stringify({ hello: 'world' })) + + const invalid = standaloneSerializer({ hello: [] }) + t.assert.deepStrictEqual(invalid, '{"hello":""}') + }) + }) + + t.test('fastify integration - writeMode', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory) + await app.ready() + }) + + await t.test('fastify integration - writeMode forces standalone', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory, { + mode: 'not-standalone', + rounding: 'ceil' + }) + + await app.ready() + }) + + await t.test('fastify integration - readMode', async t => { + t.plan(6) + + const factory = FjsStandaloneCompiler({ + readMode: true, + storeFunction () { + t.fail('read mode ON') + }, + restoreFunction (routeOpts) { + const fileName = generateFileName(routeOpts) + t.assert.ok(`restore the serializer function ${fileName}}`) + return require(path.join(__dirname, fileName)) + } + }) + + const app = buildApp(factory) + await app.ready() + + let res = await app.inject({ + url: '/foo', + method: 'POST' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ hello: 'world' })) + + res = await app.inject({ + url: '/bar?lang=it', + method: 'GET' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ lang: 'en' })) + }) + + function buildApp (factory, serializerOpts) { + const app = fastify({ + exposeHeadRoutes: false, + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + }, + serializerOpts + }) + + app.addSchema({ + $id: 'urn:schema:foo', + type: 'object', + properties: { + name: { type: 'string' }, + id: { type: 'integer' } + } + }) + + app.post('/foo', { + schema: { + response: { + 200: { + $id: 'urn:schema:response', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:foo#/properties/name' } + } + } + } + } + }, () => { return { hello: 'world' } }) + + app.get('/bar', { + schema: { + response: { + 200: { + $id: 'urn:schema:response:bar', + type: 'object', + properties: { + lang: { type: 'string', enum: ['it', 'en'] } + } + } + } + } + }, () => { return { lang: 'en' } }) + + return app + } +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05461351432d028c25868f7ab46f322548cd28ca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts @@ -0,0 +1,41 @@ +import { Options } from 'fast-json-stringify' + +type FastJsonStringifyFactory = () => SerializerSelector.SerializerFactory + +declare namespace SerializerSelector { + export type SerializerFactory = ( + externalSchemas?: unknown, + options?: Options + ) => SerializerCompiler + + export type SerializerCompiler = (routeDef: RouteDefinition) => Serializer + export type Serializer = (doc: any) => string + + export type RouteDefinition = { + method: string; + url: string; + httpStatus: string; + schema?: unknown; + } + + export type StandaloneOptions = StandaloneOptionsReadModeOn | StandaloneOptionsReadModeOff + + export type StandaloneOptionsReadModeOn = { + readMode: true; + restoreFunction?(opts: RouteDefinition): Serializer; + } + + export type StandaloneOptionsReadModeOff = { + readMode?: false | undefined; + storeFunction?(opts: RouteDefinition, schemaSerializationCode: string): void; + } + + export type { Options } + export const SerializerSelector: FastJsonStringifyFactory + export function StandaloneSerializer (options: StandaloneOptions): SerializerFactory + + export { SerializerSelector as default } +} + +declare function SerializerSelector (...params: Parameters): ReturnType +export = SerializerSelector diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..018759aadc42c09b683479fbbfc370d0dcb4b119 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts @@ -0,0 +1,142 @@ +import { expectAssignable, expectError, expectType } from 'tsd' +import SerializerSelector, { + RouteDefinition, + Serializer, + SerializerCompiler, + SerializerFactory, + SerializerSelector as SerializerSelectorNamed, + StandaloneSerializer, +} from '..' + +/** + * SerializerSelector + */ + +{ + const compiler = SerializerSelector() + expectType(compiler) +} + +{ + const compiler = SerializerSelectorNamed() + expectType(compiler) +} + +{ + const sampleSchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } + } + + const externalSchemas1 = {} + + const factory = SerializerSelector() + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectType(compiler) + const serializeFunc = compiler({ schema: sampleSchema, method: '', url: '', httpStatus: '' }) + expectType(serializeFunc) + + expectType(serializeFunc({ name: 'hello' })) +} + +/** + * StandaloneSerializer + */ + +const reader = StandaloneSerializer({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as Serializer + }, +}) +expectType(reader) + +const writer = StandaloneSerializer({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectType(writer) + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + method: '', + url: '', + httpStatus: '', + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + expectError(StandaloneSerializer({ + readMode: true, + storeFunction () { } + })) + expectError(StandaloneSerializer({ + readMode: false, + restoreFunction () {} + })) + expectError(StandaloneSerializer({ + restoreFunction () {} + })) + + expectType(StandaloneSerializer({ + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + })) + + expectType(StandaloneSerializer({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as Serializer + } + })) + + const factory = StandaloneSerializer({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + }) + expectType(factory) + + const compiler = factory(schemaMap) + expectType(compiler) + expectType(compiler(endpointSchema)) +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed5fb986ba0f12de70e2a4b7bb0fe161e7210bc8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts @@ -0,0 +1,14 @@ +import { IncomingMessage } from 'http'; + +type Forwarded = (req: IncomingMessage) => string[] + +declare namespace forwarded { + export const forwarded: Forwarded + export { forwarded as default } +} + +/** + * Get all addresses in the request used in the `X-Forwarded-For` header. + */ +declare function forwarded(...params: Parameters): ReturnType +export = forwarded diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..226c5a9dd06e93d27c1ff8f2eda25fa76fa093fb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Fastify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js new file mode 100644 index 0000000000000000000000000000000000000000..74774308f6b9121e243297f53d28272001dd6b3c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/index.js @@ -0,0 +1,357 @@ +'use strict' + +const { dequal: deepEqual } = require('dequal') +const resolvers = require('./lib/resolvers') +const errors = require('./lib/errors') + +const keywordsResolvers = { + $id: resolvers.skip, + type: resolvers.hybridArraysIntersection, + enum: resolvers.arraysIntersection, + minLength: resolvers.maxNumber, + maxLength: resolvers.minNumber, + minimum: resolvers.maxNumber, + maximum: resolvers.minNumber, + multipleOf: resolvers.commonMultiple, + exclusiveMinimum: resolvers.maxNumber, + exclusiveMaximum: resolvers.minNumber, + minItems: resolvers.maxNumber, + maxItems: resolvers.minNumber, + maxProperties: resolvers.minNumber, + minProperties: resolvers.maxNumber, + const: resolvers.allEqual, + default: resolvers.allEqual, + format: resolvers.allEqual, + required: resolvers.arraysUnion, + properties: mergeProperties, + patternProperties: mergeObjects, + additionalProperties: mergeSchemasResolver, + items: mergeItems, + additionalItems: mergeAdditionalItems, + definitions: mergeObjects, + $defs: mergeObjects, + nullable: resolvers.booleanAnd, + oneOf: mergeOneOf, + anyOf: mergeOneOf, + allOf: resolvers.arraysUnion, + not: mergeSchemasResolver, + if: mergeIfThenElseSchemas, + then: resolvers.skip, + else: resolvers.skip, + dependencies: mergeDependencies, + dependentRequired: mergeDependencies, + dependentSchemas: mergeObjects, + propertyNames: mergeSchemasResolver, + uniqueItems: resolvers.booleanOr, + contains: mergeSchemasResolver +} + +function mergeSchemasResolver (keyword, values, mergedSchema, _schemas, options) { + mergedSchema[keyword] = _mergeSchemas(values, options) +} + +function cartesianProduct (arrays) { + let result = [[]] + + for (const array of arrays) { + const temp = [] + for (const x of result) { + for (const y of array) { + temp.push([...x, y]) + } + } + result = temp + } + + return result +} + +function mergeOneOf (keyword, values, mergedSchema, _schemas, options) { + if (values.length === 1) { + mergedSchema[keyword] = values[0] + return + } + + const product = cartesianProduct(values) + const mergedOneOf = [] + for (const combination of product) { + try { + const mergedSchema = _mergeSchemas(combination, options) + if (mergedSchema !== undefined) { + mergedOneOf.push(mergedSchema) + } + } catch (error) { + // If this combination is not valid, we can ignore it. + if (error instanceof errors.MergeError) continue + throw error + } + } + mergedSchema[keyword] = mergedOneOf +} + +function getSchemaForItem (schema, index) { + const { items, additionalItems } = schema + + if (Array.isArray(items)) { + if (index < items.length) { + return items[index] + } + return additionalItems + } + + if (items !== undefined) { + return items + } + + return additionalItems +} + +function mergeItems (keyword, values, mergedSchema, schemas, options) { + let maxArrayItemsLength = 0 + for (const itemsSchema of values) { + if (Array.isArray(itemsSchema)) { + maxArrayItemsLength = Math.max(maxArrayItemsLength, itemsSchema.length) + } + } + + if (maxArrayItemsLength === 0) { + mergedSchema[keyword] = _mergeSchemas(values, options) + return + } + + const mergedItemsSchemas = [] + for (let i = 0; i < maxArrayItemsLength; i++) { + const indexItemSchemas = [] + for (const schema of schemas) { + const itemSchema = getSchemaForItem(schema, i) + if (itemSchema !== undefined) { + indexItemSchemas.push(itemSchema) + } + } + mergedItemsSchemas[i] = _mergeSchemas(indexItemSchemas, options) + } + mergedSchema[keyword] = mergedItemsSchemas +} + +function mergeAdditionalItems (keyword, values, mergedSchema, schemas, options) { + let hasArrayItems = false + for (const schema of schemas) { + if (Array.isArray(schema.items)) { + hasArrayItems = true + break + } + } + + if (!hasArrayItems) { + mergedSchema[keyword] = _mergeSchemas(values, options) + return + } + + const mergedAdditionalItemsSchemas = [] + for (const schema of schemas) { + let additionalItemsSchema = schema.additionalItems + if ( + additionalItemsSchema === undefined && + !Array.isArray(schema.items) + ) { + additionalItemsSchema = schema.items + } + if (additionalItemsSchema !== undefined) { + mergedAdditionalItemsSchemas.push(additionalItemsSchema) + } + } + + mergedSchema[keyword] = _mergeSchemas(mergedAdditionalItemsSchemas, options) +} + +function getSchemaForProperty (schema, propertyName) { + const { properties, patternProperties, additionalProperties } = schema + + if (properties?.[propertyName] !== undefined) { + return properties[propertyName] + } + + for (const pattern of Object.keys(patternProperties ?? {})) { + const regexp = new RegExp(pattern) + if (regexp.test(propertyName)) { + return patternProperties[pattern] + } + } + + return additionalProperties +} + +function mergeProperties (keyword, _values, mergedSchema, schemas, options) { + const foundProperties = {} + for (const currentSchema of schemas) { + const properties = currentSchema.properties ?? {} + for (const propertyName of Object.keys(properties)) { + if (foundProperties[propertyName] !== undefined) continue + + const propertySchema = properties[propertyName] + foundProperties[propertyName] = [propertySchema] + + for (const anotherSchema of schemas) { + if (currentSchema === anotherSchema) continue + + const propertySchema = getSchemaForProperty(anotherSchema, propertyName) + if (propertySchema !== undefined) { + foundProperties[propertyName].push(propertySchema) + } + } + } + } + + const mergedProperties = {} + for (const property of Object.keys(foundProperties)) { + const propertySchemas = foundProperties[property] + mergedProperties[property] = _mergeSchemas(propertySchemas, options) + } + mergedSchema[keyword] = mergedProperties +} + +function mergeObjects (keyword, values, mergedSchema, _schemas, options) { + const objectsProperties = {} + + for (const properties of values) { + for (const propertyName of Object.keys(properties)) { + if (objectsProperties[propertyName] === undefined) { + objectsProperties[propertyName] = [] + } + objectsProperties[propertyName].push(properties[propertyName]) + } + } + + const mergedProperties = {} + for (const propertyName of Object.keys(objectsProperties)) { + const propertySchemas = objectsProperties[propertyName] + const mergedPropertySchema = _mergeSchemas(propertySchemas, options) + mergedProperties[propertyName] = mergedPropertySchema + } + + mergedSchema[keyword] = mergedProperties +} + +function mergeIfThenElseSchemas (_keyword, _values, mergedSchema, schemas, options) { + for (let i = 0; i < schemas.length; i++) { + const subSchema = { + if: schemas[i].if, + then: schemas[i].then, + else: schemas[i].else + } + + if (subSchema.if === undefined) continue + + if (mergedSchema.if === undefined) { + mergedSchema.if = subSchema.if + if (subSchema.then !== undefined) { + mergedSchema.then = subSchema.then + } + if (subSchema.else !== undefined) { + mergedSchema.else = subSchema.else + } + continue + } + + if (mergedSchema.then !== undefined) { + mergedSchema.then = _mergeSchemas([mergedSchema.then, subSchema], options) + } + if (mergedSchema.else !== undefined) { + mergedSchema.else = _mergeSchemas([mergedSchema.else, subSchema], options) + } + } +} + +function mergeDependencies (keyword, values, mergedSchema) { + const mergedDependencies = {} + for (const dependencies of values) { + for (const propertyName of Object.keys(dependencies)) { + if (mergedDependencies[propertyName] === undefined) { + mergedDependencies[propertyName] = [] + } + const mergedPropertyDependencies = mergedDependencies[propertyName] + for (const propertyDependency of dependencies[propertyName]) { + if (!mergedPropertyDependencies.includes(propertyDependency)) { + mergedPropertyDependencies.push(propertyDependency) + } + } + } + } + mergedSchema[keyword] = mergedDependencies +} + +function _mergeSchemas (schemas, options) { + if (schemas.length === 0) return {} + if (schemas.length === 1) return schemas[0] + + const mergedSchema = {} + const keywords = {} + + let allSchemasAreTrue = true + + for (const schema of schemas) { + if (schema === false) return false + if (schema === true) continue + allSchemasAreTrue = false + + for (const keyword of Object.keys(schema)) { + if (keywords[keyword] === undefined) { + keywords[keyword] = [] + } + keywords[keyword].push(schema[keyword]) + } + } + + if (allSchemasAreTrue) return true + + for (const keyword of Object.keys(keywords)) { + const keywordValues = keywords[keyword] + const resolver = options.resolvers[keyword] ?? options.defaultResolver + resolver(keyword, keywordValues, mergedSchema, schemas, options) + } + + return mergedSchema +} + +function defaultResolver (keyword, values, mergedSchema, _schemas, options) { + const onConflict = options.onConflict ?? 'throw' + + if (values.length === 1 || onConflict === 'first') { + mergedSchema[keyword] = values[0] + return + } + + let allValuesEqual = true + for (let i = 1; i < values.length; i++) { + if (!deepEqual(values[i], values[0])) { + allValuesEqual = false + break + } + } + + if (allValuesEqual) { + mergedSchema[keyword] = values[0] + return + } + + if (onConflict === 'throw') { + throw new errors.ResolverNotFoundError(keyword, values) + } + if (onConflict === 'skip') { + return + } + throw new errors.InvalidOnConflictOptionError(onConflict) +} + +function mergeSchemas (schemas, options = {}) { + if (options.defaultResolver === undefined) { + options.defaultResolver = defaultResolver + } + + options.resolvers = { ...keywordsResolvers, ...options.resolvers } + + const mergedSchema = _mergeSchemas(schemas, options) + return mergedSchema +} + +module.exports = { mergeSchemas, keywordsResolvers, defaultResolver, ...errors } diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..0a14792e73e87a7289de5bf5452b5751de562a80 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js @@ -0,0 +1,36 @@ +'use strict' + +class MergeError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Failed to merge "${keyword}" keyword schemas.` + this.schemas = schemas + } +} + +class ResolverNotFoundError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Resolver for "${keyword}" keyword not found.` + this.schemas = schemas + } +} + +class InvalidOnConflictOptionError extends Error { + constructor (onConflict) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Invalid "onConflict" option: "${onConflict}".` + } +} + +module.exports = { + MergeError, + ResolverNotFoundError, + InvalidOnConflictOptionError +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js new file mode 100644 index 0000000000000000000000000000000000000000..4458838ed7040c8e98f293937e0ddc702203b2b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js @@ -0,0 +1,127 @@ +'use strict' + +const { dequal: deepEqual } = require('dequal') +const { MergeError } = require('./errors') + +function _arraysIntersection (arrays) { + let intersection = arrays[0] + for (let i = 1; i < arrays.length; i++) { + intersection = intersection.filter( + value => arrays[i].includes(value) + ) + } + return intersection +} + +function arraysIntersection (keyword, values, mergedSchema) { + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + mergedSchema[keyword] = intersection +} + +function hybridArraysIntersection (keyword, values, mergedSchema) { + for (let i = 0; i < values.length; i++) { + if (!Array.isArray(values[i])) { + values[i] = [values[i]] + } + } + + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + + if (intersection.length === 1) { + mergedSchema[keyword] = intersection[0] + } else { + mergedSchema[keyword] = intersection + } +} + +function arraysUnion (keyword, values, mergedSchema) { + const union = [] + + for (const array of values) { + for (const value of array) { + if (!union.includes(value)) { + union.push(value) + } + } + } + + mergedSchema[keyword] = union +} + +function minNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.min(...values) +} + +function maxNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.max(...values) +} + +function commonMultiple (keyword, values, mergedSchema) { + const gcd = (a, b) => (!b ? a : gcd(b, a % b)) + const lcm = (a, b) => (a * b) / gcd(a, b) + + let scale = 1 + for (const value of values) { + while (value * scale % 1 !== 0) { + scale *= 10 + } + } + + let multiple = values[0] * scale + for (const value of values) { + multiple = lcm(multiple, value * scale) + } + + mergedSchema[keyword] = multiple / scale +} + +function allEqual (keyword, values, mergedSchema) { + const firstValue = values[0] + for (let i = 1; i < values.length; i++) { + if (!deepEqual(values[i], firstValue)) { + throw new MergeError(keyword, values) + } + } + mergedSchema[keyword] = firstValue +} + +function skip () {} + +function booleanAnd (keyword, values, mergedSchema) { + for (const value of values) { + if (value === false) { + mergedSchema[keyword] = false + return + } + } + mergedSchema[keyword] = true +} + +function booleanOr (keyword, values, mergedSchema) { + for (const value of values) { + if (value === true) { + mergedSchema[keyword] = true + return + } + } + mergedSchema[keyword] = false +} + +module.exports = { + arraysIntersection, + hybridArraysIntersection, + arraysUnion, + minNumber, + maxNumber, + commonMultiple, + allEqual, + booleanAnd, + booleanOr, + skip +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json new file mode 100644 index 0000000000000000000000000000000000000000..01c745c28910e3fca656d992af0749df091806ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/package.json @@ -0,0 +1,67 @@ +{ + "name": "@fastify/merge-json-schemas", + "version": "0.2.1", + "description": "Builds a logical conjunction (AND) of multiple JSON schemas", + "main": "index.js", + "type": "commonjs", + "types": "types/index.d.ts", + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "npm run test:unit && npm run test:types", + "test:unit": "c8 --100 node --test", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/merge-json-schemas.git" + }, + "keywords": [ + "json", + "schema", + "merge", + "allOf" + ], + "author": "Ivan Tymoshenko ", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + }, + { + "name": "Gürgün Dayıoğlu", + "email": "hey@gurgun.day", + "url": "https://heyhey.to/G" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fastify/merge-json-schemas/issues" + }, + "homepage": "https://github.com/fastify/merge-json-schemas#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "devDependencies": { + "@fastify/pre-commit": "^2.1.0", + "c8": "^10.1.3", + "eslint": "^9.17.0", + "neostandard": "^0.12.0", + "tsd": "^0.31.2" + }, + "dependencies": { + "dequal": "^2.0.3" + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e4304ac04074ce5aa4bdceb544cba911a5f7ca94 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js @@ -0,0 +1,129 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and additionalProperties=false keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge two schemas with boolean additionalProperties', () => { + const schema1 = { + type: 'object', + additionalProperties: true + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with false value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with true value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: true + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string' + } + }) +}) + +test('should merge two additionalProperties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) + +test('should merge two additionalProperties and properties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: ['string', 'number'] } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2b2acef7eb0d040b4af2cfbcb6050cf3710c7038 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js @@ -0,0 +1,43 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and allOf keyword', () => { + const schema1 = {} + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge schemas with allOfs schemas', () => { + const schema1 = { + allOf: [ + { type: 'number', minimum: 0 } + ] + } + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'number', minimum: 0 }, + { type: 'string', const: 'foo' } + ] + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..98b3a21e71db3f47847e6dc7cef143dff0504cae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js @@ -0,0 +1,81 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and anyOf keyword', () => { + const schema1 = {} + const schema2 = { + anyOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge two schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo4'] }, + { type: 'string', enum: ['foo3'] } + ] + }) +}) + +test('should merge three schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5', 'foo7'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4', 'foo5'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7', 'foo8'] } + ] + } + + const schema3 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo3', 'foo5', 'foo7'] }, + { type: 'string', enum: ['foo2', 'foo4', 'foo6', 'foo8'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo2', 'foo4'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo5'] }, + { type: 'string', enum: ['foo4'] }, + { type: 'string', enum: ['foo3', 'foo7'] } + ] + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js new file mode 100644 index 0000000000000000000000000000000000000000..66efb05b28804c50d20f683c4d6dc0e929bf9fcd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js @@ -0,0 +1,55 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and contains keyword', () => { + const schema1 = {} + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + }) +}) + +test('should merge two contains keyword schemas', () => { + const schema1 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5, + maximum: 14 + } + } + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20791881f681bb6d04c6b30f4c8a921035aae474 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should use a custom resolver instead of default one', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + type: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'type') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { type: 'custom-type' }) +}) + +test('should use a custom resolver for unknown keyword', () => { + const schema1 = { customKeyword: 'string' } + const schema2 = { customKeyword: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { customKeyword: 'custom-type' }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js new file mode 100644 index 0000000000000000000000000000000000000000..186a13aa4141f18ee01e1dd1f8bd9053abc7ce33 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js @@ -0,0 +1,111 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') + +test('should merge an unknown keyword with an empty schema', () => { + const schema1 = {} + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown object keywords', () => { + const schema1 = { type: 'string', customKeyword: { foo: 'bar' } } + const schema2 = { type: 'string', customKeyword: { foo: 'bar' } } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: { foo: 'bar' } + }) +}) + +test('should use custom defaultResolver if passed', () => { + const schema1 = { type: 'string', customKeyword: 42 } + const schema2 = { type: 'string', customKeyword: 43 } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + defaultResolver: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, [42, 43]) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema.customKeyword = 'custom-value-42' + } + } + ) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: 'custom-value-42' + }) +}) + +test('should trow an error when merging two different unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2]) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should trow an error when merging two different unknown keywords with onConflict = throw', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'throw' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should skip the keyword schemas if onConflict = skip', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'skip' }) + assert.deepStrictEqual(mergedSchema, {}) +}) + +test('should pick first schema if onConflict = first', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'first' }) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should throw an error if pass wrong onConflict value', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'foo' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Invalid "onConflict" option: "foo".' + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a87cbcc51b87ce32e31b86b1c75410b88e9e3bf5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string default keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should merge equal string default keywords', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should throw an error if default string values are different', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'bar' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: ['foo', 'bar'] + }) +}) + +test('should throw an error if default object values are different', () => { + const schema1 = { type: 'object', default: { foo: 'bar' } } + const schema2 = { type: 'object', default: { foo: 'baz' } } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: [{ foo: 'bar' }, { foo: 'baz' }] + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2f90280b75e0040e29742d8f00ede6cae51f430d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js @@ -0,0 +1,46 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and definitions keyword', () => { + const schema1 = {} + const schema2 = { + definitions: { + foo: { type: 'string', const: 'foo' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', const: 'foo' } + } + }) +}) + +test('should merge two definition schemas', () => { + const schema1 = { + definitions: { + foo: { type: 'string', enum: ['foo', 'bar'] }, + bar: { type: 'string', enum: ['foo', 'bar'] } + } + } + const schema2 = { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + bar: { type: 'string', enum: ['foo', 'bar'] }, + baz: { type: 'string' } + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8a0dd133cce70242b005af352812873e98321599 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js @@ -0,0 +1,44 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string enum values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge equal string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge different string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo'] }) +}) + +test('should throw an error if can not merge enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['baz', 'qux'] } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "enum" keyword schemas.', + schemas: [['foo', 'bar'], ['baz', 'qux']] + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9481bb5f97339893248cbb7a56fc943700243d3e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMaximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge equal exclusiveMaximum values', () => { + const schema1 = { type: 'number', exclusiveMaximum: 42 } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge different exclusiveMaximum values', () => { + const schema1 = { type: 'integer', exclusiveMaximum: 42 } + const schema2 = { type: 'integer', exclusiveMaximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMaximum: 42 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d2de258104ce59c592dd6958900e7436f15ebbd7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMinimum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge equal exclusiveMinimum values', () => { + const schema1 = { type: 'number', exclusiveMinimum: 42 } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge different exclusiveMinimum values', () => { + const schema1 = { type: 'integer', exclusiveMinimum: 42 } + const schema2 = { type: 'integer', exclusiveMinimum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMinimum: 43 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e79e1c88addfaefd9aefccc6d11b5c97d2ded12c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js @@ -0,0 +1,36 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string format keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should merge equal string format keywords', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should throw an error if format keyword values are different', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "format" keyword schemas.', + schemas: ['date-time', 'date'] + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9221738daccfdcc0749cb0c4725bdf1e90309f78 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js @@ -0,0 +1,22 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should skip $id keyword if they are equal', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'foo', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should skip $id keyword if they are different', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'bar', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2135611a49b414f946c67991e8b20e7ef979ed3a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js @@ -0,0 +1,550 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and if/then/else keywords', () => { + const schema1 = {} + const schema2 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge if/then/else schema with an empty schema', () => { + const schema1 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + const schema2 = {} + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge two if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + }) +}) + +test('should merge three if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + const schema3 = { + type: 'object', + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + } + }) +}) + +test('should two if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/then and if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else and if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b780530370e512e815024fd974a8c021d6712bc1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js @@ -0,0 +1,152 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and items keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two equal item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two different sets of item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'boolean' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + baz: { type: 'boolean' } + } + } + }) +}) + +test('should merge two different sets of item schemas with additionalItems', () => { + const schema1 = { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + baz: { type: 'string', const: 'baz' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' }, + baz: { type: 'string' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string', const: 'baz' } + } + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..939cf29940a53858b7e92a9f55e5a71b690a41f5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge equal maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge different maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c97002fbf99021b043a54dfddb267ae6e4663180 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge equal maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge different maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5b39496bd4624a0a4b13ae8042f43955012d353 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxProperties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge equal maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge different maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4a0c982fa4360598338a9c3ce49ed83499a89e42 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge equal maximum values', () => { + const schema1 = { type: 'number', maximum: 42 } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge different maximum values', () => { + const schema1 = { type: 'integer', maximum: 42 } + const schema2 = { type: 'integer', maximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', maximum: 42 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..64a2c4458ae23e7b35ed9d7e7ed0209e3d53a07d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge equal minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge different minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 43 }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e73131d48b0262e74a9618a3d89fff2084a189df --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js @@ -0,0 +1,29 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge two "not" keyword schemas', () => { + const schema1 = { + type: 'array', + not: { + type: 'string' + } + } + const schema2 = { + type: 'array', + not: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + not: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ef5fcfd8618fc9e0451e5a72f15af88336c1a1bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and nullable = true keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: true }) +}) + +test('should merge empty schema and nullable = false keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: false } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) + +test('should merge schemas with nullable true and false values', () => { + const schema1 = { type: 'string', nullable: false } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3afa392f7faf33c707ee8fecdaf71acce4ad832c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and required keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two equal required keywords', () => { + const schema1 = { type: 'object', required: ['foo'] } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two different required keywords', () => { + const schema1 = { type: 'object', required: ['foo', 'bar'] } + const schema2 = { type: 'object', required: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo', 'bar', 'baz'] }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/README.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5757412404d4c881b2fcce5ed2f3428676808d6e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/README.md @@ -0,0 +1,141 @@ +# proxy-addr + +![CI](https://github.com/fastify/proxy-addr/workflows/CI/badge.svg) +[![NPM version](https://img.shields.io/npm/v/@fastify/proxy-addr.svg?style=flat)](https://www.npmjs.com/package/@fastify/proxy-addr) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) + +Determine address of proxied request. + +Forked from https://github.com/jshttp/proxy-addr to address https://github.com/jshttp/forwarded/pull/9. + +## Install + +```sh +$ npm i @fastify/proxy-addr +``` + +## API + + + +```js +var proxyaddr = require('@fastify/proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + + + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + + + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + + + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + + + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + + + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + + + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + + + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js new file mode 100644 index 0000000000000000000000000000000000000000..239ccf947ac53d84eaa66b7381a84e7a2d91de60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js @@ -0,0 +1,57 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'ipv4', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv4-mapped', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::ffff:7f00:1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv6', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::1", "10.0.0.1"); trust = proxyaddr.compile("::1")' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js new file mode 100644 index 0000000000000000000000000000000000000000..d584c6801d93048e64cd0b4f0a8b605c29df5ece --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js @@ -0,0 +1,78 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'trust none', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile([])' +}) + +suite.add({ + name: 'trust all', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function() {return true}' +}) + +suite.add({ + name: 'trust single', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'trust first', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function(a, i) {return i<1}' +}) + +suite.add({ + name: 'trust subnet', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1/8")' +}) + +suite.add({ + name: 'trust multiple', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile(["127.0.0.1", "10.0.0.1"])' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4fabb199f2575486f050e04e021c8777f292e852 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/index.js @@ -0,0 +1,334 @@ +/*! + * proxy-addr + * Copyright(c) 2021 Fastify collaborators + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.default = proxyaddr +module.exports.proxyaddr = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +const forwarded = require('@fastify/forwarded') +const ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +const DIGIT_REGEXP = /^\d+$/u +const isip = ipaddr.isValid +const parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +const IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + const addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + /* eslint-disable no-var */ + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + let trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + /* eslint-disable no-var */ + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + const rangeSubnets = new Array(arr.length) + + /* eslint-disable no-var */ + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + const len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + const pos = note.lastIndexOf('/') + const str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + let ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + const max = ip.kind() === 'ipv6' + ? 128 + : 32 + + let range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + const ip = parseip(netmask) + const kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + const addrs = alladdrs(req, trust) + const addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + const ip = parseip(addr) + let ipconv + const kind = ip.kind() + + /* eslint-disable no-var */ + for (var i = 0; i < subnets.length; i++) { + const subnet = subnets[i] + const subnetip = subnet[0] + const subnetkind = subnetip.kind() + const subnetrange = subnet[1] + let trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + const subnetip = subnet[0] + const subnetkind = subnetip.kind() + const subnetisipv4 = subnetkind === 'ipv4' + const subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + let ip = parseip(addr) + const kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e554f5008d04c4be28679d2b347a2a7f086c6985 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts @@ -0,0 +1,18 @@ +/// + +import { IncomingMessage } from 'http'; + +type FastifyProxyAddr = typeof proxyaddr + +declare function proxyaddr(req: IncomingMessage, trust: proxyaddr.Address | proxyaddr.Address[] | ((addr: string, i: number) => boolean)): string; + +declare namespace proxyaddr { + export function all(req: IncomingMessage, trust?: Address | Address[] | ((addr: string, i: number) => boolean)): string[]; + export function compile(val: Address | Address[]): (addr: string, i: number) => boolean; + + export type Address = 'loopback' | 'linklocal' | 'uniquelocal' | string; + + export const proxyAddr: FastifyProxyAddr + export { proxyAddr as default } +} +export = proxyaddr; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/.gitattributes b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a0e7df931f90e194cc6b80313f8f07744d9fc6d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/.gitattributes @@ -0,0 +1,2 @@ +# Set default behavior to automatically convert line endings +* text=auto eol=lf diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/HISTORY.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..bebfd46c954f035abdcababbbffb9eb825d15650 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/HISTORY.md @@ -0,0 +1,521 @@ +0.18.0 / 2022-03-23 +=================== + + * Fix emitted 416 error missing headers property + * Limit the headers removed for 304 response + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: destroy@1.2.0 + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + +0.17.2 / 2021-12-11 +=================== + + * pref: ignore empty http tokens + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: ms@2.1.3 + +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/LICENSE b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..74e960141dd38f126e61944e8a156cd19b635e6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 Douglas Christopher Wilson +Copyright (c) 2023 The Fastify Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/README.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf351e442daf70eeeddef2da5fa7659af34629b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/README.md @@ -0,0 +1,310 @@ +# @fastify/send + +[![CI](https://github.com/fastify/send/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/send/actions/workflows/ci.yml) +[![NPM version](https://img.shields.io/npm/v/@fastify/send.svg?style=flat)](https://www.npmjs.com/package/@fastify/send) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) + +Send is a library for streaming files from the file system as an HTTP response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install @fastify/send +``` + +### TypeScript + +`@types/mime@3` must be used if wanting to use TypeScript; +`@types/mime@4` removed the `mime` types. + +```bash +$ npm install -D @types/mime@3 +``` + +## API + +```js +const send = require('@fastify/send') +``` + +### send(req, path, [options]) + +Provide `statusCode`, `headers`, and `stream` for the given path to send to a +`res`. The `req` is the Node.js HTTP request and the `path `is a urlencoded path +to send (urlencoded, not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### contentType + +By default, this library uses the `mime` module to set the `Content-Type` +of the response based on the file extension of the requested file. + +To disable this functionality, set `contentType` to `false`. +The `Content-Type` header will need to be set manually if disabled. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for HTTP caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### maxContentRangeChunkSize + +Specify the maximum response content size, defaults to the entire file size. +This will be used when `acceptRanges` is true. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +##### highWaterMark + +When provided, this option sets the maximum number of bytes that the internal +buffer will hold before pausing reads from the underlying resource. +If you omit this option (or pass undefined), Node.js falls back to +its built-in default for readable binary streams. + +### .mime + +The `mime` export is the global instance of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __NODE_DEBUG__: + +``` +$ NODE_DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +const http = require('node:http') +const send = require('send') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, '/path/to/index.html') + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +const server = http.createServer(function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is an example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +const http = require('node:http') +const fs = require('node:fs') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream, type, metadata } = await send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + if(type === 'directory') { + // get directory list + const list = await readdir(metadata.path) + // render an index for the directory + res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }) + res.end(list.join('\n') + '\n') + } else { + res.writeHead(statusCode, headers) + stream.pipe(res) + } +}) + +server.listen(3000) +``` + +### Serving from a root directory with custom error-handling + +```js +const http = require('node:http') +const parseUrl = require('parseurl') +const send = require('@fastify/send') + +const server = http.createServer(async function onRequest (req, res) { + // transfer arbitrary files from within + // /www/example.com/public/* + const { statusCode, headers, stream, type, metadata } = await send(req, parseUrl(req).pathname, { root: '/www/public' }) + switch (type) { + case 'directory': { + // your custom directory handling logic: + res.writeHead(301, { + 'Location': metadata.requestPath + '/' + }) + res.end('Redirecting to ' + metadata.requestPath + '/') + break + } + case 'error': { + // your custom error-handling logic: + res.writeHead(metadata.error.status ?? 500, {}) + res.end(metadata.error.message) + break + } + default: { + // your custom headers + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + res.writeHead(statusCode, headers) + stream.pipe(res) + } + } +}) + +server.listen(3000) +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..2b56dd4a58b86a920c1f1fec5e09f62d6550d77e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const collapseLeadingSlashes = require('../lib/collapseLeadingSlashes').collapseLeadingSlashes + +const nonLeading = 'bla.json' +const hasLeading = '///./json' + +new benchmark.Suite() + .add(nonLeading, function () { collapseLeadingSlashes(nonLeading) }, { minSamples: 100 }) + .add(hasLeading, function () { collapseLeadingSlashes(hasLeading) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js new file mode 100644 index 0000000000000000000000000000000000000000..a9cbfc43022f024fa74961c07b2d1b1612d6583a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js @@ -0,0 +1,15 @@ +'use strict' + +const benchmark = require('benchmark') +const { containsDotFile } = require('../lib/containsDotFile') + +const hasDotFileSimple = '.github'.split('/') +const hasDotFile = './.github'.split('/') +const noDotFile = './index.html'.split('/') + +new benchmark.Suite() + .add(hasDotFileSimple.join('/'), function () { containsDotFile(hasDotFileSimple) }, { minSamples: 100 }) + .add(noDotFile.join('/'), function () { containsDotFile(noDotFile) }, { minSamples: 100 }) + .add(hasDotFile.join('/'), function () { containsDotFile(hasDotFile) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/eslint.config.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..89fd678fe2a82d7fe3be869fffd71b3631c61c6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..b611a9cdfd5d678f36db4ad5c5340e6e4705387b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js @@ -0,0 +1,25 @@ +'use strict' + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ + +function collapseLeadingSlashes (str) { + if ( + str[0] !== '/' || + str[1] !== '/' + ) { + return str + } + for (let i = 2, il = str.length; i < il; ++i) { + if (str[i] !== '/') { + return str.slice(i - 1) + } + } + /* c8 ignore next */ +} + +module.exports.collapseLeadingSlashes = collapseLeadingSlashes diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dcbf3250f5240df3e8364d5d8fc94ece817eedde --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js @@ -0,0 +1,103 @@ +'use strict' + +const { test } = require('node:test') +const { parseBytesRange } = require('../lib/parseBytesRange') + +test('parseBytesRange', async function (t) { + t.plan(13) + + await t.test('should return empty array if all specified ranges are invalid', function (t) { + t.plan(3) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-20'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999,1000-1499'), []) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 499, index: 0 }) + }) + + await t.test('should cap end at size', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=40-80') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 40, end: 80, index: 0 }) + }) + + await t.test('should parse str asking for last n bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-400') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 600, end: 999, index: 0 }) + }) + + await t.test('should parse str with only start', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=400-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 400, end: 999, index: 0 }) + }) + + await t.test('should parse "bytes=0-"', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 999, index: 0 }) + }) + + await t.test('should parse str with no bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-0') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 0, index: 0 }) + }) + + await t.test('should parse str asking for last byte', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-1') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 999, end: 999, index: 0 }) + }) + + await t.test('should parse str with some invalid ranges', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499,1000-,500-999') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should combine overlapping ranges', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=0-4,90-99,5-75,100-199,101-102') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 0, end: 75, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 90, end: 149, index: 1 }) + }) + + await t.test('should retain original order /1', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=90-99,5-75,100-199,101-102,0-4') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 90, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 0, end: 75, index: 1 }) + }) + + await t.test('should retain original order /2', function (t) { + t.plan(4) + const range = parseBytesRange(150, 'bytes=-1,20-100,0-1,101-120') + t.assert.deepStrictEqual(range.length, 3) + t.assert.deepStrictEqual(range[0], { start: 149, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 20, end: 120, index: 1 }) + t.assert.deepStrictEqual(range[2], { start: 0, end: 1, index: 2 }) + }) +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/send.2.test.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/send.2.test.js new file mode 100644 index 0000000000000000000000000000000000000000..957d6f5197d2bdbc7f62e612fcba40cece1b3356 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/send/test/send.2.test.js @@ -0,0 +1,977 @@ +'use strict' + +const { test } = require('node:test') +const http = require('node:http') +const path = require('node:path') +const request = require('supertest') +const send = require('../lib/send').send +const { shouldNotHaveBody, createServer, shouldNotHaveHeader } = require('./utils') + +const dateRegExp = /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/ +const fixtures = path.join(__dirname, 'fixtures') + +test('send(file)', async function (t) { + t.plan(22) + + await t.test('should stream the file contents', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Length', '4') + .expect(200, 'tobi') + }) + + await t.test('should stream a zero-length file', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/empty.txt') + .expect('Content-Length', '0') + .expect(200, '') + }) + + await t.test('should decode the given path as a URI', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%20thing.txt') + .expect(200, 'hey') + }) + + await t.test('should serve files with dots in name', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/do..ts.txt') + .expect(200, '...') + }) + + await t.test('should treat a malformed URI as a bad request', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%99thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should 400 on NULL bytes', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%00thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should treat an ENAMETOOLONG as a 404', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const path = Array(100).join('foobar') + await request(app) + .get('/' + path) + .expect(404) + }) + + await t.test('should support HEAD', async function (t) { + t.plan(1) + + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .head('/name.txt') + .expect(200) + .expect('Content-Length', '4') + .expect(shouldNotHaveBody(t)) + }) + + await t.test('should add an ETag header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('etag', /^W\/"[^"]+"$/) + }) + + await t.test('should add a Date header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('date', dateRegExp) + }) + + await t.test('should add a Last-Modified header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('last-modified', dateRegExp) + }) + + await t.test('should add a Accept-Ranges header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Accept-Ranges', 'bytes') + }) + + await t.test('should 404 if the file does not exist', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/meow') + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the filename is too long', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const longFilename = new Array(512).fill('a').join('') + + await request(app) + .get('/' + longFilename) + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the requested resource is not a directory', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/nums.txt/invalid') + .expect(404, /Not Found/) + }) + + await t.test('should not override content-type', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, { + ...headers, + 'Content-Type': 'application/x-custom' + }) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect('Content-Type', 'application/x-custom') + }) + + await t.test('should set Content-Type via mime map', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200) + + await request(app) + .get('/tobi.html') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(200) + }) + + await t.test('send directory', async function (t) { + t.plan(5) + + await t.test('should redirect directories to trailing slash', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect(301) + }) + + await t.test('should respond with an HTML redirect', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect('Content-Type', /html/) + .expect(301, />Redirecting to \/pets\/Redirecting to \/snow%20%E2%98%83\/Not Found=8.x` | `^5.x` | +| `^7.x` | `^4.x` | +| `>=5.x <7.x` | `^3.x` | +| `>=2.x <5.x` | `^2.x` | +| `^1.x` | `^1.x` | + + +Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin +in the table above. +See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details. + +## Usage + +```js +const fastify = require('fastify')({logger: true}) +const path = require('node:path') + +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', // optional: default '/' + constraints: { host: 'example.com' } // optional: default {} +}) + +fastify.get('/another/path', function (req, reply) { + reply.sendFile('myHtml.html') // serving path.join(__dirname, 'public', 'myHtml.html') directly +}) + +fastify.get('/another/patch-async', async function (req, reply) { + return reply.sendFile('myHtml.html') +}) + +fastify.get('/path/with/different/root', function (req, reply) { + reply.sendFile('myHtml.html', path.join(__dirname, 'build')) // serving a file from a different root location +}) + +fastify.get('/another/path', function (req, reply) { + reply.sendFile('myHtml.html', { cacheControl: false }) // overriding the options disabling cache-control headers +}) + +// Run the server! +fastify.listen({ port: 3000 }, (err, address) => { + if (err) throw err + // Server is now listening on ${address} +}) +``` + +### Multiple prefixed roots + +```js +const fastify = require('fastify')() +const fastifyStatic = require('@fastify/static') +const path = require('node:path') +// first plugin +fastify.register(fastifyStatic, { + root: path.join(__dirname, 'public') +}) + +// second plugin +fastify.register(fastifyStatic, { + root: path.join(__dirname, 'node_modules'), + prefix: '/node_modules/', + decorateReply: false // the reply decorator has been added by the first plugin registration +}) + +``` + +### Sending a file with `content-disposition` header + +```js +const fastify = require('fastify')() +const path = require('node:path') + +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', // optional: default '/' +}) + +fastify.get('/another/path', function (req, reply) { + reply.download('myHtml.html', 'custom-filename.html') // sending path.join(__dirname, 'public', 'myHtml.html') directly with custom filename +}) + +fastify.get('another/patch-async', async function (req, reply) { + // an async handler must always return the reply object + return reply.download('myHtml.html', 'custom-filename.html') +}) + +fastify.get('/path/without/cache/control', function (req, reply) { + reply.download('myHtml.html', { cacheControl: false }) // serving a file disabling cache-control headers +}) + +fastify.get('/path/without/cache/control', function (req, reply) { + reply.download('myHtml.html', 'custom-filename.html', { cacheControl: false }) +}) + +``` + +### Managing cache-control headers + +Production sites should use a reverse-proxy to manage caching headers. +However, here is an example of using fastify-static to host a Single Page Application (for example a [vite.js](https://vite.dev/) build) with sane caching. + +```js +fastify.register(require('@fastify/static'), { + root: path.join(import.meta.dirname, 'dist'), // import.meta.dirname node.js >= v20.11.0 + // By default all assets are immutable and can be cached for a long period due to cache bursting techniques + maxAge: '30d', + immutable: true, +}) + +// Explicitly reduce caching of assets that don't use cache bursting techniques +fastify.get('/', function (req, reply) { + // index.html should never be cached + reply.sendFile('index.html', {maxAge: 0, immutable: false}) +}) + +fastify.get('/favicon.ico', function (req, reply) { + // favicon can be cached for a short period + reply.sendFile('favicon.ico', {maxAge: '1d', immutable: false}) +}) +``` + +### Options + +#### `root` (required) + +The absolute path of the directory containing the files to serve. +The file to serve is determined by combining `req.url` with the +root directory. + +An array of directories can be provided to serve multiple static directories +under a single prefix. Files are served in a "first found, first served" manner, +so list directories in order of priority. Duplicate paths will raise an error. + +#### `prefix` + +Default: `'/'` + +A URL path prefix used to create a virtual mount path for the static directory. + +#### `constraints` + +Default: `{}` + +Constraints to add to registered routes. See Fastify's documentation for +[route constraints](https://fastify.dev/docs/latest/Reference/Routes/#constraints). + +#### `logLevel` + +Default: `info` + +Set log level for registered routes. + +#### `prefixAvoidTrailingSlash` + +Default: `false` + +If `false`, the prefix gets a trailing "/". If `true`, no trailing "/" is added to the prefix. + +#### `schemaHide` + +Default: `true` + +A flag that defines if the fastify route hide-schema attribute is hidden or not. + +#### `setHeaders` + +Default: `undefined` + +A function to set custom headers on the response. Alterations to the headers +must be done synchronously. The function is called as `fn(res, path, stat)`, +with the arguments: + +- `res` The response object. +- `path` The path of the file that is being sent. +- `stat` The stat object of the file that is being sent. + +#### `send` Options + +The following options are also supported and will be passed directly to the +[`@fastify/send`](https://www.npmjs.com/package/@fastify/send) module: + +- [`acceptRanges`](https://www.npmjs.com/package/@fastify/send#acceptranges) +- [`contentType`](https://www.npmjs.com/package/@fastify/send#contenttype) +- [`cacheControl`](https://www.npmjs.com/package/@fastify/send#cachecontrol) - Enable or disable setting Cache-Control response header (defaults to `true`). To provide a custom Cache-Control header, set this option to false +- [`dotfiles`](https://www.npmjs.com/package/@fastify/send#dotfiles) +- [`etag`](https://www.npmjs.com/package/@fastify/send#etag) +- [`extensions`](https://www.npmjs.com/package/@fastify/send#extensions) +- [`immutable`](https://www.npmjs.com/package/@fastify/send#immutable) +- [`index`](https://www.npmjs.com/package/@fastify/send#index) +- [`lastModified`](https://www.npmjs.com/package/@fastify/send#lastmodified) +- [`maxAge`](https://www.npmjs.com/package/@fastify/send#maxage) + +These options can be altered when calling `reply.sendFile('filename.html', options)` or `reply.sendFile('filename.html', 'otherfilename.html', options)` on each response. + +#### `redirect` + +Default: `false` + +If set to `true`, `@fastify/static` redirects to the directory with a trailing slash. + +This option cannot be `true` if `wildcard` is `false` and `ignoreTrailingSlash` is `true`. + +If `false`, requesting directories without a trailing slash triggers the app's 404 handler using `reply.callNotFound()`. + +#### `wildcard` + +Default: `true` + +If `true`, `@fastify/static` adds a wildcard route to serve files. +If `false`, it globs the filesystem for all defined files in the +served folder (`${root}/**/**`) and creates the necessary routes, +but will not serve newly added files. + +The default options of [`glob`](https://www.npmjs.com/package/glob) +are applied for getting the file list. + +This option cannot be `false` if `redirect` is `true` and `ignoreTrailingSlash` is `true`. + +#### `globIgnore` + +Default: `undefined` + +This is passed to [`glob`](https://www.npmjs.com/package/glob) +as the `ignore` option. It can be used to ignore files or directories +when using the `wildcard: false` option. + +#### `allowedPath` + +Default: `(pathName, root, request) => true` + +This function filters served files. Using the request object, complex path authentication is possible. +Returning `true` serves the file; returning `false` calls Fastify's 404 handler. + +#### `index` + +Default: `undefined` + +Under the hood, [`@fastify/send`](https://www.npmjs.com/package/@fastify/send) supports "index.html" files by default. +To disable this, set `false`, or supply a new index by passing a string or an array in preferred order. + +#### `serveDotFiles` + +Default: `false` + +If `true`, serves files in hidden directories (e.g., `.foo`). + +#### `list` + +Default: `undefined` + +If set, provides the directory list by calling the directory path. +Default response is JSON. + +Multi-root is not supported within the `list` option. + +If `dotfiles` is `deny` or `ignore`, dotfiles are excluded. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', + index: false + list: true +}) +``` + +Request + +```bash +GET /public +``` + +Response + +```json +{ "dirs": ["dir1", "dir2"], "files": ["file1.png", "file2.txt"] } +``` + +#### `list.format` + +Default: `json` + +Options: `html`, `json` + +Directory list can be in `html` format; in that case, `list.render` function is required. + +This option can be overridden by the URL parameter `format`. Options are `html` and `json`. + +```bash +GET /public/assets?format=json +``` + +Returns the response as JSON, regardless of `list.format`. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, 'public'), + prefix: '/public/', + list: { + format: 'html', + render: (dirs, files) => { + return ` + + + + +` + }, + } +}) +``` + +Request + +```bash +GET /public +``` + +Response + +```html + + + + +``` + +#### `list.names` + +Default: `['']` + +Directory list can respond to different routes declared in `list.names`. + +> 🛈 Note: If a file with the same name exists, the actual file is sent. + +Example: + +```js +fastify.register(require('@fastify/static'), { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'] + } +}) +``` + +Dir list respond with the same content to: + +```bash +GET /public +GET /public/ +GET /public/index +GET /public/index.json +``` + +#### `list.extendedFolderInfo` + +Default: `undefined` + +If `true`, extended information for folders will be accessible in `list.render` and the JSON response. + +```js +render(dirs, files) { + const dir = dirs[0]; + dir.fileCount // number of files in this folder + dir.totalFileCount // number of files in this folder (recursive) + dir.folderCount // number of folders in this folder + dir.totalFolderCount // number of folders in this folder (recursive) + dir.totalSize // size of all files in this folder (recursive) + dir.lastModified // most recent last modified timestamp of all files in this folder (recursive) +} +``` + +> ⚠ Warning: This will slightly decrease the performance, especially for deeply nested file structures. + +#### `list.jsonFormat` + +Default: `names` + +Options: `names`, `extended` + +Determines the output format when `json` is selected. + +`names`: +```json +{ + "dirs": [ + "dir1", + "dir2" + ], + "files": [ + "file1.txt", + "file2.txt" + ] +} +``` + +`extended`: +```json +{ + "dirs": [ + { + "name": "dir1", + "stats": { + "dev": 2100, + "size": 4096 + }, + "extendedInfo": { + "fileCount": 4, + "totalSize": 51233 + } + } + ], + "files": [ + { + "name": "file1.txt", + "stats": { + "dev": 2200, + "size": 554 + } + } + ] +} +``` + +#### `preCompressed` + +Default: `false` + +First, try to send the brotli encoded asset (if supported by `Accept-Encoding` headers), then gzip, and finally the original `pathname`. Skip compression for smaller files that do not benefit from it. + +Assume this structure with the compressed asset as a sibling of the uncompressed counterpart: + +``` +./public +├── main.js +├── main.js.br +├── main.js.gz +├── crit.css +├── crit.css.gz +└── index.html +``` + +#### Disable serving + +To use only the reply decorator without serving directories, pass `{ serve: false }`. +This prevents the plugin from serving everything under `root`. + +#### Disabling reply decorator + +The reply object is decorated with a `sendFile` function by default. To disable this, +pass `{ decorateReply: false }`. If `@fastify/static` is registered to multiple prefixes +in the same route, only one can initialize reply decorators. + +#### Handling 404s + +If a request matches the URL `prefix` but no file is found, Fastify's 404 +handler is called. Set a custom 404 handler with [`fastify.setNotFoundHandler()`](https://fastify.dev/docs/latest/Reference/Server/#setnotfoundhandler). + +When registering `@fastify/static` within an encapsulated context, the `wildcard` option may need to be set to `false` to support index resolution and nested not-found-handler: + +```js +const app = require('fastify')(); + +app.register((childContext, _, done) => { + childContext.register(require('@fastify/static'), { + root: path.join(__dirname, 'docs'), // docs is a folder that contains `index.html` and `404.html` + wildcard: false + }); + childContext.setNotFoundHandler((_, reply) => { + return reply.code(404).type('text/html').sendFile('404.html'); + }); + done(); +}, { prefix: 'docs' }); +``` + +This code will send the `index.html` for the paths `docs`, `docs/`, and `docs/index.html`. For all other `docs/` it will reply with `404.html`. + +### Handling Errors + +If an error occurs while sending a file, it is passed to Fastify's error handler. +Set a custom handler with [`fastify.setErrorHandler()`](https://fastify.dev/docs/latest/Reference/Server/#seterrorhandler). + +### Payload `stream.path` + +Access the file path inside the `onSend` hook using `payload.path`. + +```js +fastify.addHook('onSend', function (req, reply, payload, next) { + console.log(payload.path) + next() +}) +``` + +## License + +Licensed under [MIT](./LICENSE). diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/eslint.config.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..449d56aa1a2cd194743f92022da2b1f072ffd848 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/eslint.config.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + noJsx: true, + ts: true, +}) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e65211595939b7f6311ced10d0e4d0a6dd337e78 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/index.js @@ -0,0 +1,547 @@ +'use strict' + +const path = require('node:path') +const { fileURLToPath } = require('node:url') +const { statSync } = require('node:fs') +const { glob } = require('glob') +const fp = require('fastify-plugin') +const send = require('@fastify/send') +const encodingNegotiator = require('@fastify/accept-negotiator') +const contentDisposition = require('content-disposition') + +const dirList = require('./lib/dirList') + +const endForwardSlashRegex = /\/$/u +const asteriskRegex = /\*/gu + +const supportedEncodings = ['br', 'gzip', 'deflate'] +send.mime.default_type = 'application/octet-stream' + +async function fastifyStatic (fastify, opts) { + opts.root = normalizeRoot(opts.root) + checkRootPathForErrors(fastify, opts.root) + + const setHeaders = opts.setHeaders + if (setHeaders !== undefined && typeof setHeaders !== 'function') { + throw new TypeError('The `setHeaders` option must be a function') + } + + const invalidDirListOpts = dirList.validateOptions(opts) + if (invalidDirListOpts) { + throw invalidDirListOpts + } + + if (opts.dotfiles === undefined) { + opts.dotfiles = 'allow' + } + + const sendOptions = { + root: opts.root, + acceptRanges: opts.acceptRanges, + contentType: opts.contentType, + cacheControl: opts.cacheControl, + dotfiles: opts.dotfiles, + etag: opts.etag, + extensions: opts.extensions, + immutable: opts.immutable, + index: opts.index, + lastModified: opts.lastModified, + maxAge: opts.maxAge + } + + let prefix = opts.prefix ?? (opts.prefix = '/') + + if (!opts.prefixAvoidTrailingSlash) { + prefix = + prefix[prefix.length - 1] === '/' + ? prefix + : prefix + '/' + } + + // Set the schema hide property if defined in opts or true by default + const routeOpts = { + constraints: opts.constraints, + schema: { + hide: opts.schemaHide !== undefined ? opts.schemaHide : true + }, + logLevel: opts.logLevel, + errorHandler (error, request, reply) { + if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') { + reply.request.raw.destroy() + return + } + + fastify.errorHandler(error, request, reply) + } + } + + if (opts.decorateReply !== false) { + fastify.decorateReply('sendFile', function (filePath, rootPath, options) { + const opts = typeof rootPath === 'object' ? rootPath : options + const root = typeof rootPath === 'string' ? rootPath : opts?.root + pumpSendToReply( + this.request, + this, + filePath, + root || sendOptions.root, + 0, + opts + ) + return this + }) + + fastify.decorateReply( + 'download', + function (filePath, fileName, options = {}) { + const { root, ...opts } = + typeof fileName === 'object' ? fileName : options + fileName = typeof fileName === 'string' ? fileName : filePath + + // Set content disposition header + this.header('content-disposition', contentDisposition(fileName)) + + pumpSendToReply(this.request, this, filePath, root, 0, opts) + + return this + } + ) + } + + if (opts.serve !== false) { + if (opts.wildcard && typeof opts.wildcard !== 'boolean') { + throw new TypeError('"wildcard" option must be a boolean') + } + if (opts.wildcard === undefined || opts.wildcard === true) { + fastify.route({ + ...routeOpts, + method: ['HEAD', 'GET'], + path: prefix + '*', + handler (req, reply) { + pumpSendToReply(req, reply, '/' + req.params['*'], sendOptions.root) + } + }) + if (opts.redirect === true && prefix !== opts.prefix) { + fastify.get(opts.prefix, routeOpts, (req, reply) => { + reply.redirect(getRedirectUrl(req.raw.url), 301) + }) + } + } else { + const indexes = opts.index === undefined ? ['index.html'] : [].concat(opts.index) + const indexDirs = new Map() + const routes = new Set() + + const roots = Array.isArray(sendOptions.root) ? sendOptions.root : [sendOptions.root] + for (let rootPath of roots) { + rootPath = rootPath.split(path.win32.sep).join(path.posix.sep) + !rootPath.endsWith('/') && (rootPath += '/') + const files = await glob('**/**', { + cwd: rootPath, absolute: false, follow: true, nodir: true, dot: opts.serveDotFiles, ignore: opts.globIgnore + }) + + for (let file of files) { + file = file.split(path.win32.sep).join(path.posix.sep) + const route = prefix + file + + if (routes.has(route)) { + continue + } + + routes.add(route) + + setUpHeadAndGet(routeOpts, route, `/${file}`, rootPath) + + const key = path.posix.basename(route) + if (indexes.includes(key) && !indexDirs.has(key)) { + indexDirs.set(path.posix.dirname(route), rootPath) + } + } + } + + for (const [dirname, rootPath] of indexDirs.entries()) { + const pathname = dirname + (dirname.endsWith('/') ? '' : '/') + const file = '/' + pathname.replace(prefix, '') + setUpHeadAndGet(routeOpts, pathname, file, rootPath) + + if (opts.redirect === true) { + setUpHeadAndGet(routeOpts, pathname.replace(endForwardSlashRegex, ''), file.replace(endForwardSlashRegex, ''), rootPath) + } + } + } + } + + const allowedPath = opts.allowedPath + + async function pumpSendToReply ( + request, + reply, + pathname, + rootPath, + rootPathOffset = 0, + pumpOptions, + checkedEncodings + ) { + const pathnameOrig = pathname + const options = Object.assign({}, sendOptions, pumpOptions) + + if (rootPath) { + if (Array.isArray(rootPath)) { + options.root = rootPath[rootPathOffset] + } else { + options.root = rootPath + } + } + + if (allowedPath && !allowedPath(pathname, options.root, request)) { + return reply.callNotFound() + } + + let encoding + let pathnameForSend = pathname + + if (opts.preCompressed) { + /** + * We conditionally create this structure to track our attempts + * at sending pre-compressed assets + */ + if (!checkedEncodings) { + checkedEncodings = new Set() + } + + encoding = getEncodingHeader(request.headers, checkedEncodings) + + if (encoding) { + if (pathname.endsWith('/')) { + pathname = findIndexFile(pathname, options.root, options.index) + if (!pathname) { + return reply.callNotFound() + } + pathnameForSend = pathnameForSend + pathname + '.' + getEncodingExtension(encoding) + } else { + pathnameForSend = pathname + '.' + getEncodingExtension(encoding) + } + } + } + + // `send(..., path, ...)` will URI-decode path so we pass an encoded path here + const { + statusCode, + headers, + stream, + type, + metadata + } = await send(request.raw, encodeURI(pathnameForSend), options) + switch (type) { + case 'directory': { + const path = metadata.path + if (opts.list) { + await dirList.send({ + reply, + dir: path, + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + } + + if (opts.redirect === true) { + try { + reply.redirect(getRedirectUrl(request.raw.url), 301) + } /* c8 ignore start */ catch (error) { + // the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack + await reply.send(error) + } /* c8 ignore stop */ + } else { + // if is a directory path without a trailing slash, and has an index file, reply as if it has a trailing slash + if (!pathname.endsWith('/') && findIndexFile(pathname, options.root, options.index)) { + return pumpSendToReply( + request, + reply, + pathname + '/', + rootPath, + undefined, + undefined, + checkedEncodings + ) + } + + reply.callNotFound() + } + break + } + case 'error': { + if ( + statusCode === 403 && + (!options.index || !options.index.length) && + pathnameForSend[pathnameForSend.length - 1] === '/' + ) { + if (opts.list) { + await dirList.send({ + reply, + dir: dirList.path(opts.root, pathname), + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + return + } + } + + if (metadata.error.code === 'ENOENT') { + // when preCompress is enabled and the path is a directory without a trailing slash + if (opts.preCompressed && encoding) { + if (opts.redirect !== true) { + const indexPathname = findIndexFile(pathname, options.root, options.index) + if (indexPathname) { + return pumpSendToReply( + request, + reply, + pathname + '/', + rootPath, + undefined, + undefined, + checkedEncodings + ) + } + } + } + + // if file exists, send real file, otherwise send dir list if name match + if (opts.list && dirList.handle(pathname, opts.list)) { + await dirList.send({ + reply, + dir: dirList.path(opts.root, pathname), + options: opts.list, + route: pathname, + prefix, + dotfiles: opts.dotfiles + }).catch((err) => reply.send(err)) + return + } + + // root paths left to try? + if (Array.isArray(rootPath) && rootPathOffset < (rootPath.length - 1)) { + return pumpSendToReply(request, reply, pathname, rootPath, rootPathOffset + 1) + } + + if (opts.preCompressed && !checkedEncodings.has(encoding)) { + checkedEncodings.add(encoding) + return pumpSendToReply( + request, + reply, + pathnameOrig, + rootPath, + rootPathOffset, + undefined, + checkedEncodings + ) + } + + return reply.callNotFound() + } + + // The `send` library terminates the request with a 404 if the requested + // path contains a dotfile and `send` is initialized with `{dotfiles: + // 'ignore'}`. `send` aborts the request before getting far enough to + // check if the file exists (hence, a 404 `NotFoundError` instead of + // `ENOENT`). + // https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L582 + if (metadata.error.status === 404) { + return reply.callNotFound() + } + + await reply.send(metadata.error) + break + } + case 'file': { + // reply.raw.statusCode by default 200 + // when ever the user changed it, we respect the status code + // otherwise use send provided status code + const newStatusCode = reply.statusCode !== 200 ? reply.statusCode : statusCode + reply.code(newStatusCode) + if (setHeaders !== undefined) { + setHeaders(reply.raw, metadata.path, metadata.stat) + } + reply.headers(headers) + if (encoding) { + reply.header('content-type', getContentType(pathname)) + reply.header('content-encoding', encoding) + } + await reply.send(stream) + break + } + } + } + + function setUpHeadAndGet (routeOpts, route, file, rootPath) { + const toSetUp = Object.assign({}, routeOpts, { + method: ['HEAD', 'GET'], + url: route, + handler: serveFileHandler + }) + toSetUp.config = toSetUp.config || {} + toSetUp.config.file = file + toSetUp.config.rootPath = rootPath + fastify.route(toSetUp) + } + + async function serveFileHandler (req, reply) { + // TODO: remove the fallback branch when bump major + /* c8 ignore next */ + const routeConfig = req.routeOptions?.config || req.routeConfig + return pumpSendToReply(req, reply, routeConfig.file, routeConfig.rootPath) + } +} + +function normalizeRoot (root) { + if (root === undefined) { + return root + } + if (root instanceof URL && root.protocol === 'file:') { + return fileURLToPath(root) + } + if (Array.isArray(root)) { + const result = [] + for (let i = 0, il = root.length; i < il; ++i) { + if (root[i] instanceof URL && root[i].protocol === 'file:') { + result.push(fileURLToPath(root[i])) + } else { + result.push(root[i]) + } + } + + return result + } + + return root +} + +function checkRootPathForErrors (fastify, rootPath) { + if (rootPath === undefined) { + throw new Error('"root" option is required') + } + + if (Array.isArray(rootPath)) { + if (!rootPath.length) { + throw new Error('"root" option array requires one or more paths') + } + + if (new Set(rootPath).size !== rootPath.length) { + throw new Error( + '"root" option array contains one or more duplicate paths' + ) + } + + // check each path and fail at first invalid + rootPath.map((path) => checkPath(fastify, path)) + return + } + + if (typeof rootPath === 'string') { + return checkPath(fastify, rootPath) + } + + throw new Error('"root" option must be a string or array of strings') +} + +function checkPath (fastify, rootPath) { + if (typeof rootPath !== 'string') { + throw new TypeError('"root" option must be a string') + } + if (path.isAbsolute(rootPath) === false) { + throw new Error('"root" option must be an absolute path') + } + + let pathStat + + try { + pathStat = statSync(rootPath) + } catch (e) { + if (e.code === 'ENOENT') { + fastify.log.warn(`"root" path "${rootPath}" must exist`) + return + } + + throw e + } + + if (pathStat.isDirectory() === false) { + throw new Error('"root" option must point to a directory') + } +} + +function getContentType (path) { + const type = send.mime.getType(path) || send.mime.default_type + + if (!send.isUtf8MimeType(type)) { + return type + } + return `${type}; charset=utf-8` +} + +function findIndexFile (pathname, root, indexFiles = ['index.html']) { + if (Array.isArray(indexFiles)) { + return indexFiles.find(filename => { + const p = path.join(root, pathname, filename) + try { + const stats = statSync(p) + return !stats.isDirectory() + } catch { + return false + } + }) + } + /* c8 ignore next */ + return false +} + +// Adapted from https://github.com/fastify/fastify-compress/blob/665e132fa63d3bf05ad37df3c20346660b71a857/index.js#L451 +function getEncodingHeader (headers, checked) { + if (!('accept-encoding' in headers)) return + + // consider the no-preference token as gzip for downstream compat + const header = headers['accept-encoding'].toLowerCase().replace(asteriskRegex, 'gzip') + + return encodingNegotiator.negotiate( + header, + supportedEncodings.filter((enc) => !checked.has(enc)) + ) +} + +function getEncodingExtension (encoding) { + switch (encoding) { + case 'br': + return 'br' + + case 'gzip': + return 'gz' + } +} + +function getRedirectUrl (url) { + let i = 0 + // we detect how many slash before a valid path + for (; i < url.length; ++i) { + if (url[i] !== '/' && url[i] !== '\\') break + } + // turns all leading / or \ into a single / + url = '/' + url.substr(i) + try { + const parsed = new URL(url, 'http://localhost.com/') + const parsedPathname = parsed.pathname + return parsedPathname + (parsedPathname[parsedPathname.length - 1] !== '/' ? '/' : '') + (parsed.search || '') + } /* c8 ignore start */ catch { + // the try-catch here is actually unreachable, but we keep it for safety and prevent DoS attack + const err = new Error(`Invalid redirect URL: ${url}`) + err.statusCode = 400 + throw err + } /* c8 ignore stop */ +} + +module.exports = fp(fastifyStatic, { + fastify: '5.x', + name: '@fastify/static' +}) +module.exports.default = fastifyStatic +module.exports.fastifyStatic = fastifyStatic diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53d5b74ff6c62c6159e4bc86a2589291b3b4f6dc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts @@ -0,0 +1,4 @@ +export declare const pkg: { + name: string; + version: string; +}; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c82697f6c6b77ec180967fcb17ae050c8c6558e4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md @@ -0,0 +1,463 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gcp-metadata?activeTab=versions + +## [6.1.1](https://github.com/googleapis/gcp-metadata/compare/v6.1.0...v6.1.1) (2025-01-30) + + +### Bug Fixes + +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([edafa87](https://github.com/googleapis/gcp-metadata/commit/edafa87e020ffe28983048de5da183ceb0483bfa)) +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([#647](https://github.com/googleapis/gcp-metadata/issues/647)) ([ccbb98e](https://github.com/googleapis/gcp-metadata/commit/ccbb98e3519496414ab654769072d3397153b4b2)) + +## [6.1.0](https://github.com/googleapis/gcp-metadata/compare/v6.0.0...v6.1.0) (2023-11-10) + + +### Features + +* Add `universe` metadata handler ([#596](https://github.com/googleapis/gcp-metadata/issues/596)) ([0c02016](https://github.com/googleapis/gcp-metadata/commit/0c02016756754cddde6c4402fac1ceb6a318e82d)) +* Bulk Metadata Requests ([#598](https://github.com/googleapis/gcp-metadata/issues/598)) ([0a51378](https://github.com/googleapis/gcp-metadata/commit/0a513788537173570f9910d368dd36717de7233b)) + + +### Bug Fixes + +* Repo Metadata ([#595](https://github.com/googleapis/gcp-metadata/issues/595)) ([470a872](https://github.com/googleapis/gcp-metadata/commit/470a8722df2b2fb2da1b076b73414d2e28a3ff4e)) + +## [6.0.0](https://github.com/googleapis/gcp-metadata/compare/v5.3.0...v6.0.0) (2023-07-17) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) + +### Miscellaneous Chores + +* Upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) ([88ff3ff](https://github.com/googleapis/gcp-metadata/commit/88ff3ff3d9bd8be32126e7fe76cbf33e401f8db7)) + +## [5.3.0](https://github.com/googleapis/gcp-metadata/compare/v5.2.0...v5.3.0) (2023-06-28) + + +### Features + +* Metadata Server Detection Configuration ([#562](https://github.com/googleapis/gcp-metadata/issues/562)) ([8c7c715](https://github.com/googleapis/gcp-metadata/commit/8c7c715f1fc22ad65554a745a93915713ca6698f)) + +## [5.2.0](https://github.com/googleapis/gcp-metadata/compare/v5.1.0...v5.2.0) (2023-01-03) + + +### Features + +* Export `gcp-residency` tools ([#552](https://github.com/googleapis/gcp-metadata/issues/552)) ([ba9ae24](https://github.com/googleapis/gcp-metadata/commit/ba9ae24331b53199f81e97b6a88414050cfcf546)) + +## [5.1.0](https://github.com/googleapis/gcp-metadata/compare/v5.0.1...v5.1.0) (2022-12-07) + + +### Features + +* Extend GCP Residency Detection Support ([#528](https://github.com/googleapis/gcp-metadata/issues/528)) ([2b35bb0](https://github.com/googleapis/gcp-metadata/commit/2b35bb0e6fb1a18294aeeebba91a6bf7b400385a)) + +## [5.0.1](https://github.com/googleapis/gcp-metadata/compare/v5.0.0...v5.0.1) (2022-09-09) + + +### Bug Fixes + +* Remove pip install statements ([#1546](https://github.com/googleapis/gcp-metadata/issues/1546)) ([#529](https://github.com/googleapis/gcp-metadata/issues/529)) ([064c64c](https://github.com/googleapis/gcp-metadata/commit/064c64cec160ffe645e6946a5125960e3e269d7f)) + +## [5.0.0](https://github.com/googleapis/gcp-metadata/compare/v4.3.1...v5.0.0) (2022-04-22) + + +### ⚠ BREAKING CHANGES + +* drop node 10, update typescript to 4.6.3 (#519) + +### Build System + +* drop node 10, update typescript to 4.6.3 ([#519](https://github.com/googleapis/gcp-metadata/issues/519)) ([688749b](https://github.com/googleapis/gcp-metadata/commit/688749bc50407f3cd127a0b10ae09487d6fe5aea)) + +### [4.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.3.0...v4.3.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#481](https://www.github.com/googleapis/gcp-metadata/issues/481)) ([8a7965c](https://www.github.com/googleapis/gcp-metadata/commit/8a7965c47c077ef766e4b416358630c0b24b0af2)) + +## [4.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.1...v4.3.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#450](https://www.github.com/googleapis/gcp-metadata/issues/450)) ([6a0f9ad](https://www.github.com/googleapis/gcp-metadata/commit/6a0f9ad09b6d16370d08c5d60541ce3ef64a9f97)) + +### [4.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.0...v4.2.1) (2020-10-29) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#420](https://www.github.com/googleapis/gcp-metadata/issues/420)) ([b99fb07](https://www.github.com/googleapis/gcp-metadata/commit/b99fb0764b8dbb8b083f73b8007816914db4f09a)) + +## [4.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.4...v4.2.0) (2020-09-15) + + +### Features + +* add support for GCE_METADATA_HOST environment variable ([#406](https://www.github.com/googleapis/gcp-metadata/issues/406)) ([eaf128a](https://www.github.com/googleapis/gcp-metadata/commit/eaf128ad5afc4357cde72d19b017b9474c070fea)) + +### [4.1.4](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.3...v4.1.4) (2020-07-15) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to v1 ([#382](https://www.github.com/googleapis/gcp-metadata/issues/382)) ([ab4d8c3](https://www.github.com/googleapis/gcp-metadata/commit/ab4d8c3022903206d433bafc47c27815c6f85e36)) + +### [4.1.3](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.2...v4.1.3) (2020-07-13) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to ^0.4.0 ([#378](https://www.github.com/googleapis/gcp-metadata/issues/378)) ([b214280](https://www.github.com/googleapis/gcp-metadata/commit/b2142807928c8c032509277900d35fccd1023f0f)) + +### [4.1.2](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.1...v4.1.2) (2020-07-10) + + +### Bug Fixes + +* **deps:** roll back dependency gcp-metadata to ^4.1.0 ([#373](https://www.github.com/googleapis/gcp-metadata/issues/373)) ([a45adef](https://www.github.com/googleapis/gcp-metadata/commit/a45adefd92418faa08c8a5014cedb844d1eb3ae6)) + +### [4.1.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.0...v4.1.1) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#371](https://www.github.com/googleapis/gcp-metadata/issues/371)) ([5b4bb1c](https://www.github.com/googleapis/gcp-metadata/commit/5b4bb1c85e67e3ef0a6d1ec2ea316d560e03092f)) + +## [4.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.1...v4.1.0) (2020-05-05) + + +### Features + +* Introduces the GCE_METADATA_IP to allow using a different IP address for the GCE metadata server. ([#346](https://www.github.com/googleapis/gcp-metadata/issues/346)) ([ec0f82d](https://www.github.com/googleapis/gcp-metadata/commit/ec0f82d022b4b3aac95e94ee1d8e53cfac3b14a4)) + + +### Bug Fixes + +* do not check secondary host if GCE_METADATA_IP set ([#352](https://www.github.com/googleapis/gcp-metadata/issues/352)) ([64fa7d6](https://www.github.com/googleapis/gcp-metadata/commit/64fa7d68cbb76f455a3bfdcb27d58e7775eb789a)) +* warn rather than throwing when we fail to connect to metadata server ([#351](https://www.github.com/googleapis/gcp-metadata/issues/351)) ([754a6c0](https://www.github.com/googleapis/gcp-metadata/commit/754a6c07d1a72615cbb5ebf9ee04475a9a12f1c0)) + +### [4.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.0...v4.0.1) (2020-04-14) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v3 ([#326](https://www.github.com/googleapis/gcp-metadata/issues/326)) ([5667178](https://www.github.com/googleapis/gcp-metadata/commit/5667178429baff71ad5dab2a96f97f27b2106d57)) +* apache license URL ([#468](https://www.github.com/googleapis/gcp-metadata/issues/468)) ([#336](https://www.github.com/googleapis/gcp-metadata/issues/336)) ([195dcd2](https://www.github.com/googleapis/gcp-metadata/commit/195dcd2d227ba496949e7ec0dcd77e5b9269066c)) + +## [4.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.5.0...v4.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x has breaking changes; compiler now targets es2015 +* drops Node 8 from engines field (#315) + +### Features + +* drops Node 8 from engines field ([#315](https://www.github.com/googleapis/gcp-metadata/issues/315)) ([acb6233](https://www.github.com/googleapis/gcp-metadata/commit/acb62337e8ba7f0b259ae4e553f19c5786207d84)) + + +### Build System + +* switch to latest typescirpt/gts ([#317](https://www.github.com/googleapis/gcp-metadata/issues/317)) ([fbb7158](https://www.github.com/googleapis/gcp-metadata/commit/fbb7158be62c9f1949b69079e35113be1e10495c)) + +## [3.5.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.4.0...v3.5.0) (2020-03-03) + + +### Features + +* add ECONNREFUSED to list of known errors for isAvailable() ([#309](https://www.github.com/googleapis/gcp-metadata/issues/309)) ([17ff6ea](https://www.github.com/googleapis/gcp-metadata/commit/17ff6ea361d02de31463532d4ab4040bf6276e0b)) + +## [3.4.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.1...v3.4.0) (2020-02-24) + + +### Features + +* significantly increase timeout if GCF environment detected ([#300](https://www.github.com/googleapis/gcp-metadata/issues/300)) ([8e507c6](https://www.github.com/googleapis/gcp-metadata/commit/8e507c645f69a11f508884b3181dc4414e579fcc)) + +### [3.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.0...v3.3.1) (2020-01-30) + + +### Bug Fixes + +* **isAvailable:** handle EHOSTDOWN and EHOSTUNREACH error codes ([#291](https://www.github.com/googleapis/gcp-metadata/issues/291)) ([ba8d9f5](https://www.github.com/googleapis/gcp-metadata/commit/ba8d9f50eac6cf8b439c1b66c48ace146c75f6e2)) + +## [3.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.3...v3.3.0) (2019-12-16) + + +### Features + +* add environment variable for configuring environment detection ([#275](https://www.github.com/googleapis/gcp-metadata/issues/275)) ([580cfa4](https://www.github.com/googleapis/gcp-metadata/commit/580cfa4a5f5d0041aa09ae85cfc5a4575dd3957f)) +* cache response from isAvailable() method ([#274](https://www.github.com/googleapis/gcp-metadata/issues/274)) ([a05e13f](https://www.github.com/googleapis/gcp-metadata/commit/a05e13f1d1d61b1f9b9b1703bc37cdbdc022c93b)) + + +### Bug Fixes + +* fastFailMetadataRequest should not reject, if response already happened ([#273](https://www.github.com/googleapis/gcp-metadata/issues/273)) ([a6590c4](https://www.github.com/googleapis/gcp-metadata/commit/a6590c4fd8bc2dff3995c83d4c9175d5bd9f5e4a)) + +### [3.2.3](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.2...v3.2.3) (2019-12-12) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e4bf622](https://www.github.com/googleapis/gcp-metadata/commit/e4bf622e6654a51ddffc0921a15250130591db2f)) + +### [3.2.2](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.1...v3.2.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#264](https://www.github.com/googleapis/gcp-metadata/issues/264)) ([af8362b](https://www.github.com/googleapis/gcp-metadata/commit/af8362b5a35d270af00cb3696bbf7344810e9b0c)) + +### [3.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.0...v3.2.1) (2019-11-08) + + +### Bug Fixes + +* **deps:** update gaxios ([#257](https://www.github.com/googleapis/gcp-metadata/issues/257)) ([ba6e0b6](https://www.github.com/googleapis/gcp-metadata/commit/ba6e0b668635b4aa4ed10535ff021c02b2edf5ea)) + +## [3.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.1.0...v3.2.0) (2019-10-10) + + +### Features + +* add DEBUG_AUTH for digging into authentication issues ([#254](https://www.github.com/googleapis/gcp-metadata/issues/254)) ([804156d](https://www.github.com/googleapis/gcp-metadata/commit/804156d)) + +## [3.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.0.0...v3.1.0) (2019-10-07) + + +### Features + +* don't throw on ENETUNREACH ([#250](https://www.github.com/googleapis/gcp-metadata/issues/250)) ([88f2101](https://www.github.com/googleapis/gcp-metadata/commit/88f2101)) + +## [3.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.4...v3.0.0) (2019-09-17) + + +### ⚠ BREAKING CHANGES + +* isAvailable now tries both DNS and IP, choosing whichever responds first (#239) + +### Features + +* isAvailable now tries both DNS and IP, choosing whichever responds first ([#239](https://www.github.com/googleapis/gcp-metadata/issues/239)) ([25bc116](https://www.github.com/googleapis/gcp-metadata/commit/25bc116)) + +### [2.0.4](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.3...v2.0.4) (2019-09-13) + + +### Bug Fixes + +* IP address takes 15 seconds to timeout, vs., metadata returning immediately ([#235](https://www.github.com/googleapis/gcp-metadata/issues/235)) ([d04207b](https://www.github.com/googleapis/gcp-metadata/commit/d04207b)) +* use 3s timeout rather than 15 default ([#237](https://www.github.com/googleapis/gcp-metadata/issues/237)) ([231ca5c](https://www.github.com/googleapis/gcp-metadata/commit/231ca5c)) + +### [2.0.3](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.2...v2.0.3) (2019-09-12) + + +### Bug Fixes + +* use IP for metadata server ([#233](https://www.github.com/googleapis/gcp-metadata/issues/233)) ([20a15cb](https://www.github.com/googleapis/gcp-metadata/commit/20a15cb)) + +### [2.0.2](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.1...v2.0.2) (2019-08-26) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([#224](https://www.github.com/googleapis/gcp-metadata/issues/224)) ([dc758b1](https://www.github.com/googleapis/gcp-metadata/commit/dc758b1)) + +### [2.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.0...v2.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#212](https://www.github.com/googleapis/gcp-metadata/issues/212)) ([9174b43](https://www.github.com/googleapis/gcp-metadata/commit/9174b43)) + +## [2.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v1.0.0...v2.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/gcp-metadata/issues/191)) ([ac8c1ef](https://www.github.com/googleapis/gcp-metadata/commit/ac8c1ef)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/gcp-metadata/issues/194)) ([97c23c8](https://www.github.com/googleapis/gcp-metadata/commit/97c23c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v1.0.0 + +02-14-2019 16:00 PST + +### Bug Fixes +- fix: ask gaxios for text and not json ([#152](https://github.com/googleapis/gcp-metadata/pull/152)) + +### Documentation +- docs: update links in contrib guide ([#168](https://github.com/googleapis/gcp-metadata/pull/168)) +- docs: add lint/fix example to contributing guide ([#160](https://github.com/googleapis/gcp-metadata/pull/160)) + +### Internal / Testing Changes +- build: use linkinator for docs test ([#166](https://github.com/googleapis/gcp-metadata/pull/166)) +- chore(deps): update dependency @types/tmp to v0.0.34 ([#167](https://github.com/googleapis/gcp-metadata/pull/167)) +- build: create docs test npm scripts ([#165](https://github.com/googleapis/gcp-metadata/pull/165)) +- test: run system tests on GCB ([#157](https://github.com/googleapis/gcp-metadata/pull/157)) +- build: test using @grpc/grpc-js in CI ([#164](https://github.com/googleapis/gcp-metadata/pull/164)) +- chore: move CONTRIBUTING.md to root ([#162](https://github.com/googleapis/gcp-metadata/pull/162)) +- chore(deps): update dependency gcx to v0.1.1 ([#159](https://github.com/googleapis/gcp-metadata/pull/159)) +- chore(deps): update dependency gcx to v0.1.0 ([#158](https://github.com/googleapis/gcp-metadata/pull/158)) +- chore(deps): update dependency gcx to v0.0.4 ([#155](https://github.com/googleapis/gcp-metadata/pull/155)) +- chore(deps): update dependency googleapis to v37 ([#156](https://github.com/googleapis/gcp-metadata/pull/156)) +- build: ignore googleapis.com in doc link check ([#153](https://github.com/googleapis/gcp-metadata/pull/153)) +- build: check broken links in generated docs ([#149](https://github.com/googleapis/gcp-metadata/pull/149)) +- chore(build): inject yoshi automation key ([#148](https://github.com/googleapis/gcp-metadata/pull/148)) + +## v0.9.3 + +12-10-2018 16:16 PST + +### Dependencies +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) + +### Internal / Testing Changes +- fix(build): fix Kokoro release script ([#141](https://github.com/googleapis/gcp-metadata/pull/141)) +- Release v0.9.2 ([#140](https://github.com/googleapis/gcp-metadata/pull/140)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) +- Release gcp-metadata v0.9.1 ([#139](https://github.com/googleapis/gcp-metadata/pull/139)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- Sync repo build files ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.2 + +12-10-2018 14:01 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) + +## v0.9.1 + +12-10-2018 11:53 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.0 + +10-26-2018 13:10 PDT + +- feat: allow custom headers ([#109](https://github.com/googleapis/gcp-metadata/pull/109)) +- chore: update issue templates ([#108](https://github.com/googleapis/gcp-metadata/pull/108)) +- chore: remove old issue template ([#106](https://github.com/googleapis/gcp-metadata/pull/106)) +- build: run tests on node11 ([#105](https://github.com/googleapis/gcp-metadata/pull/105)) +- chores(build): do not collect sponge.xml from windows builds ([#104](https://github.com/googleapis/gcp-metadata/pull/104)) +- chores(build): run codecov on continuous builds ([#102](https://github.com/googleapis/gcp-metadata/pull/102)) +- chore(deps): update dependency nock to v10 ([#103](https://github.com/googleapis/gcp-metadata/pull/103)) +- chore: update new issue template ([#101](https://github.com/googleapis/gcp-metadata/pull/101)) +- build: fix codecov uploading on Kokoro ([#97](https://github.com/googleapis/gcp-metadata/pull/97)) +- Update kokoro config ([#95](https://github.com/googleapis/gcp-metadata/pull/95)) +- Update CI config ([#93](https://github.com/googleapis/gcp-metadata/pull/93)) +- Update kokoro config ([#91](https://github.com/googleapis/gcp-metadata/pull/91)) +- Re-generate library using /synth.py ([#90](https://github.com/googleapis/gcp-metadata/pull/90)) +- test: remove appveyor config ([#89](https://github.com/googleapis/gcp-metadata/pull/89)) +- Update kokoro config ([#88](https://github.com/googleapis/gcp-metadata/pull/88)) +- Enable prefer-const in the eslint config ([#87](https://github.com/googleapis/gcp-metadata/pull/87)) +- Enable no-var in eslint ([#86](https://github.com/googleapis/gcp-metadata/pull/86)) + +### New Features + +A new option, `headers`, has been added to allow metadata queries to be sent with custom headers. + +## v0.8.0 + +**This release has breaking changes**. Please take care when upgrading to the latest version. + +#### Dropped support for Node.js 4.x and 9.x +This library is no longer tested against versions 4.x and 9.x of Node.js. Please upgrade to the latest supported LTS version! + +#### Return type of `instance()` and `project()` has changed +The `instance()` and `project()` methods are much more selective about which properties they will accept. + +The only accepted properties are `params` and `properties`. The `instance()` and `project()` methods also now directly return the data instead of a response object. + +#### Changes in how large number valued properties are handled + +Previously large number-valued properties were being silently losing precision when +returned by this library (as a number). In the cases where a number valued property +returned by the metadata service is too large to represent as a JavaScript number, we +will now return the value as a BigNumber (from the bignumber.js) library. Numbers that +do fit into the JavaScript number range will continue to be returned as numbers. +For more details see [#74](https://github.com/googleapis/gcp-metadata/pull/74). + +### Breaking Changes +- chore: drop support for node.js 4 and 9 ([#68](https://github.com/googleapis/gcp-metadata/pull/68)) +- fix: quarantine axios config ([#62](https://github.com/googleapis/gcp-metadata/pull/62)) + +### Implementation Changes +- fix: properly handle large numbers in responses ([#74](https://github.com/googleapis/gcp-metadata/pull/74)) + +### Dependencies +- chore(deps): update dependency pify to v4 ([#73](https://github.com/googleapis/gcp-metadata/pull/73)) + +### Internal / Testing Changes +- Move to the new github org ([#84](https://github.com/googleapis/gcp-metadata/pull/84)) +- Update CI config ([#83](https://github.com/googleapis/gcp-metadata/pull/83)) +- Retry npm install in CI ([#81](https://github.com/googleapis/gcp-metadata/pull/81)) +- Update CI config ([#79](https://github.com/googleapis/gcp-metadata/pull/79)) +- chore(deps): update dependency nyc to v13 ([#77](https://github.com/googleapis/gcp-metadata/pull/77)) +- add key for system tests +- increase kitchen test timeout +- add a lint npm script +- update npm scripts +- add a synth file and run it ([#75](https://github.com/googleapis/gcp-metadata/pull/75)) +- chore(deps): update dependency assert-rejects to v1 ([#72](https://github.com/googleapis/gcp-metadata/pull/72)) +- chore: ignore package-log.json ([#71](https://github.com/googleapis/gcp-metadata/pull/71)) +- chore: update renovate config ([#70](https://github.com/googleapis/gcp-metadata/pull/70)) +- test: throw on deprecation +- chore(deps): update dependency typescript to v3 ([#67](https://github.com/googleapis/gcp-metadata/pull/67)) +- chore: make it OSPO compliant ([#66](https://github.com/googleapis/gcp-metadata/pull/66)) +- chore(deps): update dependency gts to ^0.8.0 ([#65](https://github.com/googleapis/gcp-metadata/pull/65)) diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js new file mode 100644 index 0000000000000000000000000000000000000000..882a9a9188fab3ff33fcdb50b6c4f3c389e404c4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js @@ -0,0 +1,209 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsRequestSigner = void 0; +const crypto_1 = require("../crypto/crypto"); +/** AWS Signature Version 4 signing algorithm identifier. */ +const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; +/** + * The termination string for the AWS credential scope value as defined in + * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + */ +const AWS_REQUEST_TYPE = 'aws4_request'; +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +class AwsRequestSigner { + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials, region) { + this.getCredentials = getCredentials; + this.region = region; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + async getRequestOptions(amzOptions) { + if (!amzOptions.url) { + throw new Error('"url" is required in "amzOptions"'); + } + // Stringify JSON requests. This will be set in the request body of the + // generated signed request. + const requestPayloadData = typeof amzOptions.data === 'object' + ? JSON.stringify(amzOptions.data) + : amzOptions.data; + const url = amzOptions.url; + const method = amzOptions.method || 'GET'; + const requestPayload = amzOptions.body || requestPayloadData; + const additionalAmzHeaders = amzOptions.headers; + const awsSecurityCredentials = await this.getCredentials(); + const uri = new URL(url); + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.substr(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders, + }); + // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. + const headers = Object.assign( + // Add x-amz-date if available. + headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { + Authorization: headerMap.authorizationHeader, + host: uri.host, + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + Object.assign(headers, { + 'x-amz-security-token': awsSecurityCredentials.token, + }); + } + const awsSignedReq = { + url, + method: method, + headers, + }; + if (typeof requestPayload !== 'undefined') { + awsSignedReq.body = requestPayload; + } + return awsSignedReq; + } +} +exports.AwsRequestSigner = AwsRequestSigner; +/** + * Creates the HMAC-SHA256 hash of the provided message using the + * provided key. + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The HMAC-SHA256 key to use. + * @param msg The message to hash. + * @return The computed hash bytes. + */ +async function sign(crypto, key, msg) { + return await crypto.signWithHmacSha256(key, msg); +} +/** + * Calculates the signing key used to calculate the signature for + * AWS Signature Version 4 based on: + * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The AWS secret access key. + * @param dateStamp The '%Y%m%d' date format. + * @param region The AWS region. + * @param serviceName The AWS service name, eg. sts. + * @return The signing key bytes. + */ +async function getSigningKey(crypto, key, dateStamp, region, serviceName) { + const kDate = await sign(crypto, `AWS4${key}`, dateStamp); + const kRegion = await sign(crypto, kDate, region); + const kService = await sign(crypto, kRegion, serviceName); + const kSigning = await sign(crypto, kService, 'aws4_request'); + return kSigning; +} +/** + * Generates the authentication header map needed for generating the AWS + * Signature Version 4 signed request. + * + * @param option The options needed to compute the authentication header map. + * @return The AWS authentication header map which constitutes of the following + * components: amz-date, authorization header and canonical query string. + */ +async function generateAuthenticationHeaderMap(options) { + const additionalAmzHeaders = options.additionalAmzHeaders || {}; + const requestPayload = options.requestPayload || ''; + // iam.amazonaws.com host => iam service. + // sts.us-east-2.amazonaws.com => sts service. + const serviceName = options.host.split('.')[0]; + const now = new Date(); + // Format: '%Y%m%dT%H%M%SZ'. + const amzDate = now + .toISOString() + .replace(/[-:]/g, '') + .replace(/\.[0-9]+/, ''); + // Format: '%Y%m%d'. + const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); + // Change all additional headers to be lower case. + const reformattedAdditionalAmzHeaders = {}; + Object.keys(additionalAmzHeaders).forEach(key => { + reformattedAdditionalAmzHeaders[key.toLowerCase()] = + additionalAmzHeaders[key]; + }); + // Add AWS token if available. + if (options.securityCredentials.token) { + reformattedAdditionalAmzHeaders['x-amz-security-token'] = + options.securityCredentials.token; + } + // Header keys need to be sorted alphabetically. + const amzHeaders = Object.assign({ + host: options.host, + }, + // Previously the date was not fixed with x-amz- and could be provided manually. + // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req + reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); + let canonicalHeaders = ''; + const signedHeadersList = Object.keys(amzHeaders).sort(); + signedHeadersList.forEach(key => { + canonicalHeaders += `${key}:${amzHeaders[key]}\n`; + }); + const signedHeaders = signedHeadersList.join(';'); + const payloadHash = await options.crypto.sha256DigestHex(requestPayload); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + const canonicalRequest = `${options.method}\n` + + `${options.canonicalUri}\n` + + `${options.canonicalQuerystring}\n` + + `${canonicalHeaders}\n` + + `${signedHeaders}\n` + + `${payloadHash}`; + const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + const stringToSign = `${AWS_ALGORITHM}\n` + + `${amzDate}\n` + + `${credentialScope}\n` + + (await options.crypto.sha256DigestHex(canonicalRequest)); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); + const signature = await sign(options.crypto, signingKey, stringToSign); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html + const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; + return { + // Do not return x-amz-date if date is available. + amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring, + }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js new file mode 100644 index 0000000000000000000000000000000000000000..4554e03e4b498bcc27e6c481fc3f03dfc6472996 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js @@ -0,0 +1,117 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Compute = void 0; +const gaxios_1 = require("gaxios"); +const gcpMetadata = require("gcp-metadata"); +const oauth2client_1 = require("./oauth2client"); +class Compute extends oauth2client_1.OAuth2Client { + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; + this.serviceAccountEmail = options.serviceAccountEmail || 'default'; + this.scopes = Array.isArray(options.scopes) + ? options.scopes + : options.scopes + ? [options.scopes] + : []; + } + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath, + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(','), + }; + } + data = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError) { + e.message = `Could not refresh access token: ${e.message}`; + this.wrapError(e); + } + throw e; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res: null }; + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath, + }; + idToken = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof Error) { + e.message = `Could not fetch ID token: ${e.message}`; + } + throw e; + } + return idToken; + } + wrapError(e) { + const res = e.response; + if (res && res.status) { + e.status = res.status; + if (res.status === 403) { + e.message = + 'A Forbidden error was returned while attempting to retrieve an access ' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have the correct permission scopes specified: ' + + e.message; + } + else if (res.status === 404) { + e.message = + 'A Not Found error was returned while attempting to retrieve an access' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have any permission scopes specified: ' + + e.message; + } + } + } +} +exports.Compute = Compute; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62a2fa41464d57aa6850157938c567be5e0fa3e5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts @@ -0,0 +1,79 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { AwsSecurityCredentialsSupplier } from './awsclient'; +import { AwsSecurityCredentials } from './awsrequestsigner'; +/** + * Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}. + */ +export interface DefaultAwsSecurityCredentialsSupplierOptions { + /** + * The URL to call to retrieve the active AWS region. + **/ + regionUrl?: string; + /** + * The URL to call to retrieve AWS security credentials. + **/ + securityCredentialsUrl?: string; + /** + ** The URL to call to retrieve the IMDSV2 session token. + **/ + imdsV2SessionTokenUrl?: string; + /** + * Additional Gaxios options to use when making requests to the AWS metadata + * endpoints. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +export declare class DefaultAwsSecurityCredentialsSupplier implements AwsSecurityCredentialsSupplier { + #private; + private readonly regionUrl?; + private readonly securityCredentialsUrl?; + private readonly imdsV2SessionTokenUrl?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts: DefaultAwsSecurityCredentialsSupplierOptions); + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion(context: ExternalAccountSupplierContext): Promise; + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..83d95bc38ae5b14428a997deab9f50ff7e61ebb0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js @@ -0,0 +1,196 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _DefaultAwsSecurityCredentialsSupplier_instances, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultAwsSecurityCredentialsSupplier = void 0; +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +class DefaultAwsSecurityCredentialsSupplier { + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts) { + _DefaultAwsSecurityCredentialsSupplier_instances.add(this); + this.regionUrl = opts.regionUrl; + this.securityCredentialsUrl = opts.securityCredentialsUrl; + this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + async getAwsRegion(context) { + // Priority order for region determination: + // AWS_REGION > AWS_DEFAULT_REGION > metadata server. + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get); + } + const metadataHeaders = {}; + if (!__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + if (!this.regionUrl) { + throw new Error('Unable to determine AWS region due to missing ' + + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: 'GET', + responseType: 'text', + headers: metadataHeaders, + }; + const response = await context.transporter.request(opts); + // Remove last character. For example, if us-east-2b is returned, + // the region would be us-east-2. + return response.data.substr(0, response.data.length - 1); + } + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + async getAwsSecurityCredentials(context) { + // Check environment variables for permanent credentials first. + // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get); + } + const metadataHeaders = {}; + if (this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + // Since the role on a VM can change, we don't need to cache it. + const roleName = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context.transporter); + // Temporary credentials typically last for several hours. + // Expiration is returned in response. + // Consider future optimization of this logic to cache AWS tokens + // until their natural expiration. + const awsCreds = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token, + }; + } +} +exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; +_DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = +/** + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the IMDSv2 Session Token. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: 'PUT', + responseType: 'text', + headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = +/** + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the assigned role to the current + * AWS VM. This is needed for calling the security-credentials endpoint. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName(headers, transporter) { + if (!this.securityCredentialsUrl) { + throw new Error('Unable to determine AWS role name due to missing ' + + '"options.credential_source.url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.securityCredentialsUrl, + method: 'GET', + responseType: 'text', + headers: headers, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = +/** + * Retrieves the temporary AWS credentials by calling the security-credentials + * endpoint as specified in the `credential_source` object. + * @param roleName The role attached to the current VM. + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the temporary AWS credentials + * needed for creating the GetCallerIdentity signed request. + */ +async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const response = await transporter.request({ + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + responseType: 'json', + headers: headers, + }); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get() { + // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. + // Only one is required. + return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); +}, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get() { + // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. + if (process.env['AWS_ACCESS_KEY_ID'] && + process.env['AWS_SECRET_ACCESS_KEY']) { + return { + accessKeyId: process.env['AWS_ACCESS_KEY_ID'], + secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], + token: process.env['AWS_SESSION_TOKEN'], + }; + } + return null; +}; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fc01c6d7c24f53d7f21d5e5fa5c5807a4d09bf9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts @@ -0,0 +1,10 @@ +export declare enum GCPEnv { + APP_ENGINE = "APP_ENGINE", + KUBERNETES_ENGINE = "KUBERNETES_ENGINE", + CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", + COMPUTE_ENGINE = "COMPUTE_ENGINE", + CLOUD_RUN = "CLOUD_RUN", + NONE = "NONE" +} +export declare function clear(): void; +export declare function getEnv(): Promise; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js new file mode 100644 index 0000000000000000000000000000000000000000..54860ead367e2f018f4bfb886f24dfa170d09e0c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js @@ -0,0 +1,64 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExternalAccountClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const identitypoolclient_1 = require("./identitypoolclient"); +const awsclient_1 = require("./awsclient"); +const pluggable_auth_client_1 = require("./pluggable-auth-client"); +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +class ExternalAccountClient { + constructor() { + throw new Error('ExternalAccountClients should be initialized via: ' + + 'ExternalAccountClient.fromJSON(), ' + + 'directly via explicit constructors, eg. ' + + 'new AwsClient(options), new IdentityPoolClient(options), new' + + 'PluggableAuthClientOptions, or via ' + + 'new GoogleAuth(options).getClient()'); + } + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options, additionalOptions) { + var _a, _b; + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { + return new awsclient_1.AwsClient(options, additionalOptions); + } + else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions); + } + else { + return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); + } + } + else { + return null; + } + } +} +exports.ExternalAccountClient = ExternalAccountClient; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..abf9bed14a3bfd107877e15bfc8b88d3fc1472fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js @@ -0,0 +1,81 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var _a, _b, _c; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileSubjectTokenSupplier = void 0; +const util_1 = require("util"); +const fs = require("fs"); +// fs.readfile is undefined in browser karma tests causing +// `npm run browser-test` to fail as test.oauth2.ts imports this file via +// src/index.ts. +// Fallback to void function to avoid promisify throwing a TypeError. +const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); +const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); +const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class FileSubjectTokenSupplier { + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts) { + this.filePath = opts.filePath; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + } + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + let parsedFilePath = this.filePath; + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + parsedFilePath = await realpath(parsedFilePath); + if (!(await lstat(parsedFilePath)).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + let subjectToken; + const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); + if (this.formatType === 'text') { + subjectToken = rawText; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const json = JSON.parse(rawText); + subjectToken = json[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source file'); + } + return subjectToken; + } +} +exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..099c280b39318a10d12ba8f48170a91fbba249b1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts @@ -0,0 +1,375 @@ +import { GaxiosOptions, GaxiosResponse } from 'gaxios'; +import * as stream from 'stream'; +import { DefaultTransporter, Transporter } from '../transporters'; +import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials'; +import { IdTokenClient } from './idtokenclient'; +import { GCPEnv } from './envDetect'; +import { JWT, JWTOptions } from './jwtclient'; +import { Headers, OAuth2ClientOptions } from './oauth2client'; +import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient'; +import { Impersonated, ImpersonatedOptions } from './impersonated'; +import { ExternalAccountClientOptions } from './externalclient'; +import { BaseExternalAccountClient } from './baseexternalclient'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient'; +import { AnyAuthClient } from '..'; +/** + * Defines all types of explicit clients that are determined via ADC JSON + * config file. + */ +export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated; +export interface ProjectIdCallback { + (err?: Error | null, projectId?: string | null): void; +} +export interface CredentialCallback { + (err: Error | null, result?: JSONClient): void; +} +export interface ADCCallback { + (err: Error | null, credential?: AuthClient, projectId?: string | null): void; +} +export interface ADCResponse { + credential: AuthClient; + projectId: string | null; +} +export interface GoogleAuthOptions { + /** + * An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}. + */ + apiKey?: string; + /** + * An `AuthClient` to use + */ + authClient?: T; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFilename?: string; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFile?: string; + /** + * Object containing client_email and private_key properties, or the + * external account client options. + * Cannot be used with {@link GoogleAuthOptions.apiKey `apiKey`}. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + credentials?: JWTInput | ExternalAccountClientOptions; + /** + * Options object passed to the constructor of the client + */ + clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions | ImpersonatedOptions; + /** + * Required scopes for the desired API request + */ + scopes?: string | string[]; + /** + * Your project ID. + */ + projectId?: string; + /** + * The default service domain for a given Cloud universe. + * + * This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain` + * property and will be set for all generated {@link AuthClient}s. + */ + universeDomain?: string; +} +export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"; +export declare const GoogleAuthExceptionMessages: { + readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together."; + readonly NO_PROJECT_ID_FOUND: string; + readonly NO_CREDENTIALS_FOUND: string; + readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information."; + readonly NO_UNIVERSE_DOMAIN_FOUND: string; +}; +export declare class GoogleAuth { + #private; + transporter?: Transporter; + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + private checkIsGCE?; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + get isGCE(): boolean | undefined; + private _findProjectIdPromise?; + private _cachedProjectId?; + jsonContent: JWTInput | ExternalAccountClientOptions | null; + apiKey: string | null; + cachedCredential: AnyAuthClient | T | null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes?: string | string[]; + private keyFilename?; + private scopes?; + private clientOptions; + /** + * Export DefaultTransporter as a static property of the class. + */ + static DefaultTransporter: typeof DefaultTransporter; + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts?: GoogleAuthOptions); + setGapicJWTValues(client: JWT): void; + /** + * Obtains the default project ID for the application. + * + * Retrieves in the following order of precedence: + * - The `projectId` provided in this object's construction + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + private getProjectIdOptional; + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + private findAndCacheProjectId; + private getProjectIdAsync; + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + getUniverseDomainFromMetadataServer(): Promise; + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + getUniverseDomain(): Promise; + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + private getAnyScopes; + /** + * Obtains the default service-level credentials for the application. + * @param callback Optional callback. + * @returns Promise that resolves with the ADCResponse (if no callback was + * passed). + */ + getApplicationDefault(): Promise; + getApplicationDefault(callback: ADCCallback): void; + getApplicationDefault(options: AuthClientOptions): Promise; + getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void; + private getApplicationDefaultAsync; + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + _checkIsGCE(): Promise; + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + _getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise; + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated; + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient; + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + private _cacheClientFromJSON; + /** + * Create a credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: CredentialCallback): void; + fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise; + fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void; + private fromStreamAsync; + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey: string, options?: AuthClientOptions): JWT; + /** + * Determines whether the current operating system is Windows. + * @api private + */ + private _isWindows; + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + private getDefaultServiceProjectId; + /** + * Loads the project id from environment variables. + * @api private + */ + private getProductionProjectId; + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + private getFileProjectId; + /** + * Gets the project ID from external account client if available. + */ + private getExternalAccountClientProjectId; + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + private getGCEProjectId; + /** + * The callback function handles a credential object that contains the + * client_email and private_key (if exists). + * getCredentials first checks if the client is using an external account and + * uses the service account email in place of client_email. + * If that doesn't exist, it checks for these values from the user JSON. + * If the user JSON doesn't exist, and the environment is on GCE, it gets the + * client_email from the cloud metadata server. + * @param callback Callback that handles the credential object that contains + * a client_email and optional private key, or the error. + * returned + */ + getCredentials(): Promise; + getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void; + private getCredentialsAsync; + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + getClient(): Promise; + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + getIdTokenClient(targetAudience: string): Promise; + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + getAccessToken(): Promise; + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + getRequestHeaders(url?: string): Promise; + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + authorizeRequest(opts: { + url?: string; + uri?: string; + headers?: Headers; + }): Promise<{ + url?: string; + uri?: string; + headers?: Headers; + }>; + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * Determine the compute environment in which the code is running. + */ + getEnv(): Promise; + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + sign(data: string, endpoint?: string): Promise; + private signBlob; +} +export interface SignBlobResponse { + keyId: string; + signedBlob: string; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b2e6c14ad3c3df6e9a34abd332d008b9fc8b65e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts @@ -0,0 +1,102 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +import { SnakeToCamelObject } from '../util'; +export type SubjectTokenFormatType = 'json' | 'text'; +export interface SubjectTokenJsonResponse { + [key: string]: string; +} +/** + * Supplier interface for subject tokens. This can be implemented to + * return a subject token which can then be exchanged for a GCP token by an + * {@link IdentityPoolClient}. + */ +export interface SubjectTokenSupplier { + /** + * Gets a valid subject token for the requested external account identity. + * Note that these are not cached by the calling {@link IdentityPoolClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested subject token string. + */ + getSubjectToken: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * Url-sourced/file-sourced credentials json interface. + * This is used for K8s and Azure workloads. + */ +export interface IdentityPoolClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve identity pool credentials. A valid credential + * source or a subject token supplier must be specified. + */ + credential_source?: { + /** + * The file location to read the subject token from. Either this or a URL + * should be specified. + */ + file?: string; + /** + * The URL to call to retrieve the subject token. Either this or a file + * location should be specified. + */ + url?: string; + /** + * Optional headers to send on the request to the specified URL. + */ + headers?: { + [key: string]: string; + }; + /** + * The format that the subject token is in the file or the URL response. + * If not provided, will default to reading the text string directly. + */ + format?: { + /** + * The format type. Can either be 'text' or 'json'. + */ + type: SubjectTokenFormatType; + /** + * The field name containing the subject token value if the type is 'json'. + */ + subject_token_field_name?: string; + }; + }; + /** + * The subject token supplier to call to retrieve the subject token to exchange + * for a GCP access token. Either this or a valid credential source should + * be specified. + */ + subject_token_supplier?: SubjectTokenSupplier; +} +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +export declare class IdentityPoolClient extends BaseExternalAccountClient { + private readonly subjectTokenSupplier; + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: IdentityPoolClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js new file mode 100644 index 0000000000000000000000000000000000000000..c2e2307484b91da59be1e6e9520f6e706b3bc009 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js @@ -0,0 +1,107 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IdentityPoolClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const util_1 = require("../util"); +const filesubjecttokensupplier_1 = require("./filesubjecttokensupplier"); +const urlsubjecttokensupplier_1 = require("./urlsubjecttokensupplier"); +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const subjectTokenSupplier = opts.get('subject_token_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !subjectTokenSupplier) { + throw new Error('A credential source or subject token supplier must be specified.'); + } + if (credentialSource && subjectTokenSupplier) { + throw new Error('Only one of credential source or subject token supplier can be specified.'); + } + if (subjectTokenSupplier) { + this.subjectTokenSupplier = subjectTokenSupplier; + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); + // Text is the default format type. + const formatType = formatOpts.get('type') || 'text'; + const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); + if (formatType !== 'json' && formatType !== 'text') { + throw new Error(`Invalid credential_source format "${formatType}"`); + } + if (formatType === 'json' && !formatSubjectTokenFieldName) { + throw new Error('Missing subject_token_field_name for JSON credential_source format'); + } + const file = credentialSourceOpts.get('file'); + const url = credentialSourceOpts.get('url'); + const headers = credentialSourceOpts.get('headers'); + if (file && url) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + else if (file && !url) { + this.credentialSourceType = 'file'; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + }); + } + else if (!file && url) { + this.credentialSourceType = 'url'; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url: url, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers: headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, + }); + } + else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + } + } + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + return this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + } +} +exports.IdentityPoolClient = IdentityPoolClient; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..311d29d078f95274db9727eecd55571bf39010c2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts @@ -0,0 +1,27 @@ +import { OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface IdTokenOptions extends OAuth2ClientOptions { + /** + * The client to make the request to fetch an ID token. + */ + idTokenProvider: IdTokenProvider; + /** + * The audience to use when requesting an ID token. + */ + targetAudience: string; +} +export interface IdTokenProvider { + fetchIdToken: (targetAudience: string) => Promise; +} +export declare class IdTokenClient extends OAuth2Client { + targetAudience: string; + idTokenProvider: IdTokenProvider; + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options: IdTokenOptions); + protected getRequestMetadataAsync(url?: string | null): Promise; + private getIdTokenExpiryDate; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js new file mode 100644 index 0000000000000000000000000000000000000000..46c07c98f877ed996b868a5a3e09f1361633f7bf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js @@ -0,0 +1,186 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; +const oauth2client_1 = require("./oauth2client"); +const gaxios_1 = require("gaxios"); +const util_1 = require("../util"); +exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; +class Impersonated extends oauth2client_1.OAuth2Client { + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options = {}) { + var _a, _b, _c, _d, _e, _f; + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { + expiry_date: 1, + refresh_token: 'impersonated-placeholder', + }; + this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); + this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; + this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; + this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; + this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; + const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (!usingExplicitUniverseDomain) { + // override the default universe with the source's universe + this.universeDomain = this.sourceClient.universeDomain; + } + else if (this.sourceClient.universeDomain !== this.universeDomain) { + // non-default universe and is not matching the source - this could be a credential leak + throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + } + this.endpoint = + (_f = options.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`; + } + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + async sign(blobToSign) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:signBlob`; + const body = { + delegates: this.delegates, + payload: Buffer.from(blobToSign).toString('base64'), + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data; + } + /** The service account email to be impersonated. */ + getTargetPrincipal() { + return this.targetPrincipal; + } + /** + * Refreshes the access token. + */ + async refreshToken() { + var _a, _b, _c, _d, _e, _f; + try { + await this.sourceClient.getAccessToken(); + const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; + const u = `${this.endpoint}/v1/${name}:generateAccessToken`; + const body = { + delegates: this.delegates, + scope: this.targetScopes, + lifetime: this.lifetime + 's', + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + const tokenResponse = res.data; + this.credentials.access_token = tokenResponse.accessToken; + this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); + return { + tokens: this.credentials, + res, + }; + } + catch (error) { + if (!(error instanceof Error)) + throw error; + let status = 0; + let message = ''; + if (error instanceof gaxios_1.GaxiosError) { + status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; + message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; + } + if (status && message) { + error.message = `${status}: unable to impersonate: ${message}`; + throw error; + } + else { + error.message = `unable to impersonate: ${error}`; + throw error; + } + } + } + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + async fetchIdToken(targetAudience, options) { + var _a, _b; + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:generateIdToken`; + const body = { + delegates: this.delegates, + audience: targetAudience, + includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true, + useEmailAzp: (_b = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _b !== void 0 ? _b : true, + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data.token; + } +} +exports.Impersonated = Impersonated; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9244650289d612825dc171aeddd2ee9d3170c3a3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts @@ -0,0 +1,62 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { Headers } from './oauth2client'; +export interface Claims { + [index: string]: string; +} +export declare class JWTAccess { + email?: string | null; + key?: string | null; + keyId?: string | null; + projectId?: string; + eagerRefreshThresholdMillis: number; + private cache; + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number); + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url?: string, scopes?: string | string[]): string; + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url?: string, additionalClaims?: Claims, scopes?: string | string[]): Headers; + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + private static getExpirationTime; + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWTAccess credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7080d080a99d8b9d5e43b9d615d50dadfe0a18e2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts @@ -0,0 +1,575 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import * as querystring from 'querystring'; +import { JwkCertificate } from '../crypto/crypto'; +import { BodyResponseCallback } from '../transporters'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { Credentials } from './credentials'; +import { LoginTicket } from './loginticket'; +/** + * The results from the `generateCodeVerifierAsync` method. To learn more, + * See the sample: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ +export interface CodeVerifierResults { + /** + * The code verifier that will be used when calling `getToken` to obtain a new + * access token. + */ + codeVerifier: string; + /** + * The code_challenge that should be sent with the `generateAuthUrl` call + * to obtain a verifiable authentication url. + */ + codeChallenge?: string; +} +export interface Certificates { + [index: string]: string | JwkCertificate; +} +export interface PublicKeys { + [index: string]: string; +} +export interface Headers { + [index: string]: string; +} +export declare enum CodeChallengeMethod { + Plain = "plain", + S256 = "S256" +} +export declare enum CertificateFormat { + PEM = "PEM", + JWK = "JWK" +} +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +export declare enum ClientAuthentication { + ClientSecretPost = "ClientSecretPost", + ClientSecretBasic = "ClientSecretBasic", + None = "None" +} +export interface GetTokenOptions { + code: string; + codeVerifier?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. Must match any client_id option passed to + * a corresponding call to generateAuthUrl. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value passed into the constructor + * will be used if not provided. Must match any redirect_uri option passed to + * a corresponding call to generateAuthUrl. + */ + redirect_uri?: string; +} +export interface TokenInfo { + /** + * The application that is the intended user of the access token. + */ + aud: string; + /** + * This value lets you correlate profile information from multiple Google + * APIs. It is only present in the response if you included the profile scope + * in your request in step 1. The field value is an immutable identifier for + * the logged-in user that can be used to create and manage user sessions in + * your application. The identifier is the same regardless of which client ID + * is used to retrieve it. This enables multiple applications in the same + * organization to correlate profile information. + */ + user_id?: string; + /** + * An array of scopes that the user granted access to. + */ + scopes: string[]; + /** + * The datetime when the token becomes invalid. + */ + expiry_date: number; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub?: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The user's email address. This value may not be unique to this user and + * is not suitable for use as a primary key. Provided only if your scope + * included the email scope value. + */ + email?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; +} +export interface GenerateAuthUrlOpts { + /** + * Recommended. Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The hd (hosted domain) parameter streamlines the login process for G Suite + * hosted accounts. By including the domain of the G Suite user (for example, + * mycollege.edu), you can indicate that the account selection UI should be + * optimized for accounts at that domain. To optimize for G Suite accounts + * generally instead of just one domain, use an asterisk: hd=*. + * Don't rely on this UI optimization to control who can access your app, + * as client-side requests can be modified. Be sure to validate that the + * returned ID token has an hd claim value that matches what you expect + * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is + * contained within a security token from Google, so the value can be trusted. + */ + hd?: string; + /** + * The 'response_type' will always be set to 'CODE'. + */ + response_type?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. You can find this value in the API Console. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value must exactly match one of the + * 'redirect_uri' values listed for your project in the API Console. Note that + * the http or https scheme, case, and trailing slash ('/') must all match. + * The value passed into the constructor will be used if not provided. + */ + redirect_uri?: string; + /** + * Required. A space-delimited list of scopes that identify the resources that + * your application could access on the user's behalf. These values inform the + * consent screen that Google displays to the user. Scopes enable your + * application to only request access to the resources that it needs while + * also enabling users to control the amount of access that they grant to your + * application. Thus, there is an inverse relationship between the number of + * scopes requested and the likelihood of obtaining user consent. The + * OAuth 2.0 API Scopes document provides a full list of scopes that you might + * use to access Google APIs. We recommend that your application request + * access to authorization scopes in context whenever possible. By requesting + * access to user data in context, via incremental authorization, you help + * users to more easily understand why your application needs the access it is + * requesting. + */ + scope?: string[] | string; + /** + * Recommended. Specifies any string value that your application uses to + * maintain state between your authorization request and the authorization + * server's response. The server returns the exact value that you send as a + * name=value pair in the hash (#) fragment of the 'redirect_uri' after the + * user consents to or denies your application's access request. You can use + * this parameter for several purposes, such as directing the user to the + * correct resource in your application, sending nonces, and mitigating + * cross-site request forgery. Since your redirect_uri can be guessed, using a + * state value can increase your assurance that an incoming connection is the + * result of an authentication request. If you generate a random string or + * encode the hash of a cookie or another value that captures the client's + * state, you can validate the response to additionally ensure that the + * request and response originated in the same browser, providing protection + * against attacks such as cross-site request forgery. See the OpenID Connect + * documentation for an example of how to create and confirm a state token. + */ + state?: string; + /** + * Optional. Enables applications to use incremental authorization to request + * access to additional scopes in context. If you set this parameter's value + * to true and the authorization request is granted, then the new access token + * will also cover any scopes to which the user previously granted the + * application access. See the incremental authorization section for examples. + */ + include_granted_scopes?: boolean; + /** + * Optional. If your application knows which user is trying to authenticate, + * it can use this parameter to provide a hint to the Google Authentication + * Server. The server uses the hint to simplify the login flow either by + * prefilling the email field in the sign-in form or by selecting the + * appropriate multi-login session. Set the parameter value to an email + * address or sub identifier, which is equivalent to the user's Google ID. + */ + login_hint?: string; + /** + * Optional. A space-delimited, case-sensitive list of prompts to present the + * user. If you don't specify this parameter, the user will be prompted only + * the first time your app requests access. Possible values are: + * + * 'none' - Donot display any authentication or consent screens. Must not be + * specified with other values. + * 'consent' - Prompt the user for consent. + * 'select_account' - Prompt the user to select an account. + */ + prompt?: string; + /** + * Recommended. Specifies what method was used to encode a 'code_verifier' + * that will be used during authorization code exchange. This parameter must + * be used with the 'code_challenge' parameter. The value of the + * 'code_challenge_method' defaults to "plain" if not present in the request + * that includes a 'code_challenge'. The only supported values for this + * parameter are "S256" or "plain". + */ + code_challenge_method?: CodeChallengeMethod; + /** + * Recommended. Specifies an encoded 'code_verifier' that will be used as a + * server-side challenge during authorization code exchange. This parameter + * must be used with the 'code_challenge' parameter described above. + */ + code_challenge?: string; + /** + * A way for developers and/or the auth team to provide a set of key value + * pairs to be added as query parameters to the authorization url. + */ + [key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput]; +} +export interface AccessTokenResponse { + access_token: string; + expiry_date: number; +} +export interface GetRefreshHandlerCallback { + (): Promise; +} +export interface GetTokenCallback { + (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface GetTokenResponse { + tokens: Credentials; + res: GaxiosResponse | null; +} +export interface GetAccessTokenCallback { + (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void; +} +export interface GetAccessTokenResponse { + token?: string | null; + res?: GaxiosResponse | null; +} +export interface RefreshAccessTokenCallback { + (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenResponse { + credentials: Credentials; + res: GaxiosResponse | null; +} +export interface RequestMetadataResponse { + headers: Headers; + res?: GaxiosResponse | null; +} +export interface RequestMetadataCallback { + (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse | null): void; +} +export interface GetFederatedSignonCertsCallback { + (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse | null): void; +} +export interface FederatedSignonCertsResponse { + certs: Certificates; + format: CertificateFormat; + res?: GaxiosResponse | null; +} +export interface GetIapPublicKeysCallback { + (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse | null): void; +} +export interface IapPublicKeysResponse { + pubkeys: PublicKeys; + res?: GaxiosResponse | null; +} +export interface RevokeCredentialsResult { + success: boolean; +} +export interface VerifyIdTokenOptions { + idToken: string; + audience?: string | string[]; + maxExpiry?: number; +} +export interface OAuth2ClientEndpoints { + /** + * The endpoint for viewing access token information + * + * @example + * 'https://oauth2.googleapis.com/tokeninfo' + */ + tokenInfoUrl: string | URL; + /** + * The base URL for auth endpoints. + * + * @example + * 'https://accounts.google.com/o/oauth2/v2/auth' + */ + oauth2AuthBaseUrl: string | URL; + /** + * The base endpoint for token retrieval + * . + * @example + * 'https://oauth2.googleapis.com/token' + */ + oauth2TokenUrl: string | URL; + /** + * The base endpoint to revoke tokens. + * + * @example + * 'https://oauth2.googleapis.com/revoke' + */ + oauth2RevokeUrl: string | URL; + /** + * Sign on certificates in PEM format. + * + * @example + * 'https://www.googleapis.com/oauth2/v1/certs' + */ + oauth2FederatedSignonPemCertsUrl: string | URL; + /** + * Sign on certificates in JWK format. + * + * @example + * 'https://www.googleapis.com/oauth2/v3/certs' + */ + oauth2FederatedSignonJwkCertsUrl: string | URL; + /** + * IAP Public Key URL. + * This URL contains a JSON dictionary that maps the `kid` claims to the public key values. + * + * @example + * 'https://www.gstatic.com/iap/verify/public_key' + */ + oauth2IapPublicKeyUrl: string | URL; +} +export interface OAuth2ClientOptions extends AuthClientOptions { + clientId?: string; + clientSecret?: string; + redirectUri?: string; + /** + * Customizable endpoints. + */ + endpoints?: Partial; + /** + * The allowed OAuth2 token issuers. + */ + issuers?: string[]; + /** + * The client authentication type. Supported values are basic, post, and none. + * Defaults to post if not provided. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ + clientAuthentication?: ClientAuthentication; +} +export type RefreshOptions = Pick; +export declare class OAuth2Client extends AuthClient { + private redirectUri?; + private certificateCache; + private certificateExpiry; + private certificateCacheFormat; + protected refreshTokenPromises: Map>; + readonly endpoints: Readonly; + readonly issuers: string[]; + readonly clientAuthentication: ClientAuthentication; + _clientId?: string; + _clientSecret?: string; + refreshHandler?: GetRefreshHandlerCallback; + /** + * Handles OAuth2 flow for Google APIs. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param redirectUri The URI to redirect to after completing the auth + * request. + * @param opts optional options for overriding the given parameters. + * @constructor + */ + constructor(options?: OAuth2ClientOptions); + constructor(clientId?: string, clientSecret?: string, redirectUri?: string); + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + /** + * Clock skew - five minutes in seconds + */ + private static readonly CLOCK_SKEW_SECS_; + /** + * The default max Token Lifetime is one day in seconds + */ + private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts?: GenerateAuthUrlOpts): string; + generateCodeVerifier(): void; + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + generateCodeVerifierAsync(): Promise; + /** + * Gets the access token for the given code. + * @param code The authorization code. + * @param callback Optional callback fn. + */ + getToken(code: string): Promise; + getToken(options: GetTokenOptions): Promise; + getToken(code: string, callback: GetTokenCallback): void; + getToken(options: GetTokenOptions, callback: GetTokenCallback): void; + private getTokenAsync; + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + protected refreshToken(refreshToken?: string | null): Promise; + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Retrieves the access token using refresh token + * + * @param callback callback + */ + refreshAccessToken(): Promise; + refreshAccessToken(callback: RefreshAccessTokenCallback): void; + private refreshAccessTokenAsync; + /** + * Get a non-expired access token, after refreshing if necessary + * + * @param callback Callback to call with the access token + */ + getAccessToken(): Promise; + getAccessToken(callback: GetAccessTokenCallback): void; + private getAccessTokenAsync; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + getRequestHeaders(url?: string): Promise; + protected getRequestMetadataAsync(url?: string | URL | null): Promise; + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token: string): string; + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token: string): URL; + /** + * Revokes the access given to token. + * @param token The existing token to be revoked. + * @param callback Optional callback fn. + */ + revokeToken(token: string): GaxiosPromise; + revokeToken(token: string, callback: BodyResponseCallback): void; + /** + * Revokes access token and clears the credentials object + * @param callback callback + */ + revokeCredentials(): GaxiosPromise; + revokeCredentials(callback: BodyResponseCallback): void; + private revokeCredentialsAsync; + /** + * Provides a request implementation with OAuth 2.0 flow. If credentials have + * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically + * asks for a new access token and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return Request object + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Verify id token is token by checking the certs and audience + * @param options that contains all options. + * @param callback Callback supplying GoogleLogin if successful + */ + verifyIdToken(options: VerifyIdTokenOptions): Promise; + verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void; + private verifyIdTokenAsync; + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + getTokenInfo(accessToken: string): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getFederatedSignonCerts(): Promise; + getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void; + getFederatedSignonCertsAsync(): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getIapPublicKeys(): Promise; + getIapPublicKeys(callback: GetIapPublicKeysCallback): void; + getIapPublicKeysAsync(): Promise; + verifySignedJwtWithCerts(): void; + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise; + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + private processAndValidateRefreshHandler; + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + protected isTokenExpiring(): boolean; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5ddd024541de64f6c5d2522c2d20cb97b19fc91 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts @@ -0,0 +1,51 @@ +import { ExecutableResponse } from './executable-response'; +/** + * Defines the options used for the PluggableAuthHandler class. + */ +export interface PluggableAuthHandlerOptions { + /** + * The command used to retrieve the third party token. + */ + command: string; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis: number; + /** + * The path to file to check for cached executable response. + */ + outputFile?: string; +} +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +export declare class PluggableAuthHandler { + private readonly commandComponents; + private readonly timeoutMillis; + private readonly outputFile?; + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options: PluggableAuthHandlerOptions); + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap: Map): Promise; + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + retrieveCachedResponse(): Promise; + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + private static parseCommand; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0ed1aef7b80c761959d78be32aaf71c00da7564 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts @@ -0,0 +1,27 @@ +import { Crypto, JwkCertificate } from '../crypto'; +export declare class BrowserCrypto implements Crypto { + constructor(); + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + private static padBase64; + verify(pubkey: JwkCertificate, data: string, signature: string): Promise; + sign(privateKey: JwkCertificate, data: string): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..ccc6b5713d3d115862cf61bb4b2c20f321bb580e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js @@ -0,0 +1,126 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BrowserCrypto = void 0; +// This file implements crypto functions we need using in-browser +// SubtleCrypto interface `window.crypto.subtle`. +const base64js = require("base64-js"); +const crypto_1 = require("../crypto"); +class BrowserCrypto { + constructor() { + if (typeof window === 'undefined' || + window.crypto === undefined || + window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } + } + async sha256DigestBase64(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); + } + randomBytesBase64(count) { + const array = new Uint8Array(count); + window.crypto.getRandomValues(array); + return base64js.fromByteArray(array); + } + static padBase64(base64) { + // base64js requires padding, so let's add some '=' + while (base64.length % 4 !== 0) { + base64 += '='; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); + // SubtleCrypto's verify method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); + return result; + } + async sign(privateKey, data) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); + // SubtleCrypto's sign method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); + } + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text) { + const uint8array = new TextEncoder().encode(text); + const result = base64js.fromByteArray(uint8array); + return result; + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + // Convert key, if provided in ArrayBuffer format, to string. + const rawKey = typeof key === 'string' + ? key + : String.fromCharCode(...new Uint16Array(key)); + const enc = new TextEncoder(); + const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { + name: 'HMAC', + hash: { + name: 'SHA-256', + }, + }, false, ['sign']); + return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); + } +} +exports.BrowserCrypto = BrowserCrypto; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7897f68b675209f5faec410f47d15cd4163f0b9c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts @@ -0,0 +1,44 @@ +export interface JwkCertificate { + kty: string; + alg: string; + use?: string; + kid: string; + n: string; + e: string; +} +export interface CryptoSigner { + update(data: string): void; + sign(key: string, outputFormat: string): string; +} +export interface Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(n: number): string; + verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise; + sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} +export declare function createCrypto(): Crypto; +export declare function hasBrowserCrypto(): boolean; +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a56b117df31c920faa2878a714b5f9c8a6635ec --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts @@ -0,0 +1,25 @@ +import { Crypto } from '../crypto'; +export declare class NodeCrypto implements Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + verify(pubkey: string, data: string | Buffer, signature: string): Promise; + sign(privateKey: string, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd44dc5efa414866b0604a09bc8776d61a0dedd9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts @@ -0,0 +1,33 @@ +import { GoogleAuth } from './auth/googleauth'; +export * as gcpMetadata from 'gcp-metadata'; +export * as gaxios from 'gaxios'; +import { AuthClient } from './auth/authclient'; +export { AuthClient, DEFAULT_UNIVERSE } from './auth/authclient'; +export { Compute, ComputeOptions } from './auth/computeclient'; +export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials'; +export { GCPEnv } from './auth/envDetect'; +export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth'; +export { IAMAuth, RequestMetadata } from './auth/iam'; +export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient'; +export { Claims, JWTAccess } from './auth/jwtaccess'; +export { JWT, JWTOptions } from './auth/jwtclient'; +export { Impersonated, ImpersonatedOptions } from './auth/impersonated'; +export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, ClientAuthentication, } from './auth/oauth2client'; +export { LoginTicket, TokenPayload } from './auth/loginticket'; +export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient'; +export { AwsClient, AwsClientOptions, AwsSecurityCredentialsSupplier, } from './auth/awsclient'; +export { AwsSecurityCredentials, AwsRequestSigner, } from './auth/awsrequestsigner'; +export { IdentityPoolClient, IdentityPoolClientOptions, SubjectTokenSupplier, } from './auth/identitypoolclient'; +export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient'; +export { BaseExternalAccountClient, BaseExternalAccountClientOptions, SharedExternalAccountClientOptions, ExternalAccountSupplierContext, IamGenerateAccessTokenResponse, } from './auth/baseexternalclient'; +export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient'; +export { PluggableAuthClient, PluggableAuthClientOptions, ExecutableError, } from './auth/pluggable-auth-client'; +export { PassThroughClient } from './auth/passthrough'; +export { DefaultTransporter } from './transporters'; +type ALL_EXPORTS = (typeof import('./'))[keyof typeof import('./')]; +/** + * A union type for all {@link AuthClient `AuthClient`}s. + */ +export type AnyAuthClient = InstanceType>; +declare const auth: GoogleAuth; +export { auth, GoogleAuth }; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff55f9f6be91c7e83505b8e60c9053f6fc03afa7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts @@ -0,0 +1,29 @@ +import * as tty from 'node:tty'; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +export declare class Colours { + static enabled: boolean; + static reset: string; + static bright: string; + static dim: string; + static red: string; + static green: string; + static yellow: string; + static blue: string; + static magenta: string; + static cyan: string; + static white: string; + static grey: string; + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream: tty.WriteStream): boolean; + static refresh(): void; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js new file mode 100644 index 0000000000000000000000000000000000000000..5132d72d481abe6dee1e997b9fff47811a509008 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js @@ -0,0 +1,80 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Colours = void 0; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +class Colours { + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream) { + return (stream.isTTY && + (typeof stream.getColorDepth === 'function' + ? stream.getColorDepth() > 2 + : true)); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process.stderr); + if (!this.enabled) { + Colours.reset = ''; + Colours.bright = ''; + Colours.dim = ''; + Colours.red = ''; + Colours.green = ''; + Colours.yellow = ''; + Colours.blue = ''; + Colours.magenta = ''; + Colours.cyan = ''; + Colours.white = ''; + Colours.grey = ''; + } + else { + Colours.reset = '\u001b[0m'; + Colours.bright = '\u001b[1m'; + Colours.dim = '\u001b[2m'; + Colours.red = '\u001b[31m'; + Colours.green = '\u001b[32m'; + Colours.yellow = '\u001b[33m'; + Colours.blue = '\u001b[34m'; + Colours.magenta = '\u001b[35m'; + Colours.cyan = '\u001b[36m'; + Colours.white = '\u001b[37m'; + Colours.grey = '\u001b[90m'; + } + } +} +exports.Colours = Colours; +Colours.enabled = false; +Colours.reset = ''; +Colours.bright = ''; +Colours.dim = ''; +Colours.red = ''; +Colours.green = ''; +Colours.yellow = ''; +Colours.blue = ''; +Colours.magenta = ''; +Colours.cyan = ''; +Colours.white = ''; +Colours.grey = ''; +Colours.refresh(); +//# sourceMappingURL=colours.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dbfe6032d981380d5362883e532f18e19ac31b38 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map @@ -0,0 +1 @@ +{"version":3,"file":"colours.js","sourceRoot":"","sources":["../../src/colours.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAUjC;;;;;;;GAOG;AACH,MAAa,OAAO;IAelB;;;OAGG;IACH,MAAM,CAAC,SAAS,CAAC,MAAuB;QACtC,OAAO,CACL,MAAM,CAAC,KAAK;YACZ,CAAC,OAAO,MAAM,CAAC,aAAa,KAAK,UAAU;gBACzC,CAAC,CAAC,MAAM,CAAC,aAAa,EAAE,GAAG,CAAC;gBAC5B,CAAC,CAAC,IAAI,CAAC,CACV,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO;QACZ,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,OAAO,CAAC,KAAK,GAAG,EAAE,CAAC;YACnB,OAA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G,EAAE,CAAC;AACV,aAAK,GAAG,EAAE,CAAC;AACX,YAAI,GAAG,EAAE,CAAC;AA6CnB,OAAO,CAAC,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a2d5d17a875fa7eeb66b01062414409251c5898c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js @@ -0,0 +1,31 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./logging-utils"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..edf4a2f1f1dc905dfd0f5593949b5e543d7d7e0f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;AAEjC,kDAAgC"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..1f205b9c2c4841ec53fa8593f05c6bf4429bdaf4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js @@ -0,0 +1,406 @@ +"use strict"; +// Copyright 2021-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; +exports.getNodeBackend = getNodeBackend; +exports.getDebugBackend = getDebugBackend; +exports.getStructuredBackend = getStructuredBackend; +exports.setBackend = setBackend; +exports.log = log; +const node_events_1 = require("node:events"); +const process = __importStar(require("node:process")); +const util = __importStar(require("node:util")); +const colours_1 = require("./colours"); +// Some functions (as noted) are based on the Node standard library, from +// the following file: +// +// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "event you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +var LogSeverity; +(function (LogSeverity) { + LogSeverity["DEFAULT"] = "DEFAULT"; + LogSeverity["DEBUG"] = "DEBUG"; + LogSeverity["INFO"] = "INFO"; + LogSeverity["WARNING"] = "WARNING"; + LogSeverity["ERROR"] = "ERROR"; +})(LogSeverity || (exports.LogSeverity = LogSeverity = {})); +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +class AdhocDebugLogger extends node_events_1.EventEmitter { + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + // Also add an instance pointer back to us. + instance: this, + // And pull over the EventEmitter functionality. + on: (event, listener) => this.on(event, listener), + }); + // Convenience methods for log levels. + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace) => log(namespace, this.func); + } + invoke(fields, ...args) { + // Push out any upstream logger first. + if (this.upstream) { + this.upstream(fields, ...args); + } + // Emit sink events. + this.emit('log', fields, args); + } + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); + } +} +exports.AdhocDebugLogger = AdhocDebugLogger; +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +exports.placeholder = new AdhocDebugLogger('', () => { }).func; +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +class DebugLogBackendBase { + constructor() { + var _a; + this.cached = new Map(); + this.filters = []; + this.filtersSet = false; + // Look for the Node config variable for what systems to enable. We'll store + // these for the log method below, which will call setFilters() once. + let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; + if (nodeFlag === 'all') { + nodeFlag = '*'; + } + this.filters = nodeFlag.split(','); + } + log(namespace, fields, ...args) { + try { + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; + } + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); + } + logger(fields, ...args); + } + catch (e) { + // Silently ignore all errors; we don't want them to interfere with + // the user's running app. + // e; + console.error(e); + } + } +} +exports.DebugLogBackendBase = DebugLogBackendBase; +// The basic backend. This one definitely works, but it's less feature-filled. +// +// Rather than using util.debuglog, this implements the same basic logic directly. +// The reason for this decision is that debuglog checks the value of the +// NODE_DEBUG environment variable before any user code runs; we therefore +// can't pipe our own enables into it (and util.debuglog will never print unless +// the user duplicates it into NODE_DEBUG, which isn't reasonable). +// +class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + // Default to allowing all systems, since we gate earlier based on whether the + // variable is empty. + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => { }; + } + return (fields, ...args) => { + var _a; + // TODO: `fields` needs to be turned into a string here, one way or another. + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; + break; + default: + level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; + break; + } + const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length + ? JSON.stringify(filteredFields) + : ''; + const fieldsColour = fieldsJson + ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` + : ''; + console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); + }; + } + // Regexp patterns below are from here: + // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 + setFilters() { + const totalFilters = this.filters.join(','); + const regexp = totalFilters + .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^'); + this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); + } +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +function getNodeBackend() { + return new NodeBackend(); +} +class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; + } + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + // TODO: `fields` needs to be turned into a string here. + debugLogger(args[0], ...args.slice(1)); + }; + } + setFilters() { + var _a; + const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; + process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; + } +} +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); +} +/** + * This pretty much works like the Node logger, but it outputs structured + * logging JSON matching Google Cloud's ingestion specs. Rather than handling + * its own output, it wraps another backend. The passed backend must be a subclass + * of `DebugLogBackendBase` (any of the backends exposed by this package will work). + */ +class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a; + super(); + this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend(); + } + makeLogger(namespace) { + const debugLogger = this.upstream.makeLogger(namespace); + return (fields, ...args) => { + var _a; + const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; + const json = Object.assign({ + severity, + message: util.format(...args), + }, fields); + const jsonString = JSON.stringify(json); + debugLogger(fields, jsonString); + }; + } + setFilters() { + this.upstream.setFilters(); + } +} +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); +} +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +exports.env = { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', +}; +// Keep a copy of all namespaced loggers so users can reliably .on() them. +// Note that these cached functions will need to deal with changes in the backend. +const loggerCache = new Map(); +// Our current global backend. This might be: +let cachedBackend = undefined; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); +} +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +function log(namespace, parent) { + // If the enable flag isn't set, do nothing. + const enablesFlag = process.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; + } + // This might happen mostly if the typings are dropped in a user's code, + // or if they're calling from JavaScript. + if (!namespace) { + return exports.placeholder; + } + // Handle sub-loggers. + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; + } + // Reuse loggers so things like event sinks are persistent. + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; + } + // Do we have a backend yet? + if (cachedBackend === null) { + // Explicitly disabled. + return exports.placeholder; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + // The logger is further wrapped so we can handle the backend changing out. + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + // Did the user pass a custom backend? + if (cachedBackend === null) { + // Explicitly disabled. + return; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; +} +//# sourceMappingURL=logging-utils.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82da9ab790e59035d03b9884c7e7a1c55599e02d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts @@ -0,0 +1,45 @@ +/** + * Simplified interface analogous to the tc39 Temporal.Duration + * parameter to from(). This doesn't support the full gamut (years, days). + */ +export interface DurationLike { + hours?: number; + minutes?: number; + seconds?: number; + millis?: number; +} +/** + * Simplified list of values to pass to Duration.totalOf(). This + * list is taken from the tc39 Temporal.Duration proposal, but + * larger and smaller units have been left off. + */ +export type TotalOfUnit = 'hour' | 'minute' | 'second' | 'millisecond'; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +export declare class Duration { + private millis; + private static secondInMillis; + private static minuteInMillis; + private static hourInMillis; + private constructor(); + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf: TotalOfUnit): number; + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike: DurationLike): Duration; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js new file mode 100644 index 0000000000000000000000000000000000000000..fa59c24a98d71e7416ae6eef792b03be2279d466 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js @@ -0,0 +1,68 @@ +"use strict"; +// Copyright 2022-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Duration = void 0; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +class Duration { + constructor(millis) { + this.millis = millis; + } + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf) { + switch (totalOf) { + case 'hour': + return this.millis / Duration.hourInMillis; + case 'minute': + return this.millis / Duration.minuteInMillis; + case 'second': + return this.millis / Duration.secondInMillis; + case 'millisecond': + return this.millis; + default: + throw new Error(`Invalid unit in call to totalOf(): ${totalOf}`); + } + } + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike) { + var _a, _b, _c, _d; + let millis = (_a = durationLike.millis) !== null && _a !== void 0 ? _a : 0; + millis += ((_b = durationLike.seconds) !== null && _b !== void 0 ? _b : 0) * Duration.secondInMillis; + millis += ((_c = durationLike.minutes) !== null && _c !== void 0 ? _c : 0) * Duration.minuteInMillis; + millis += ((_d = durationLike.hours) !== null && _d !== void 0 ? _d : 0) * Duration.hourInMillis; + return new Duration(millis); + } +} +exports.Duration = Duration; +Duration.secondInMillis = 1000; +Duration.minuteInMillis = Duration.secondInMillis * 60; +Duration.hourInMillis = Duration.minuteInMillis * 60; +//# sourceMappingURL=temporal.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000000000000000000000000000000000000..aae9799c1a8798d5899ffed6deda4c98b7007b48 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..567ff5da58e83683bec0ea9e86221041ddf9435f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2863dd9c318754a77c6bfb57ec5e7db8759abd8b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000000000000000000000000000000000000..f38d2ee19e7d3597c8a3fc18cb275c5028164b1f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5586dd3d054861bcb4d30439ea14b6def606f57f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function get() { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function get() { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function get() { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function get() { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function get() { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function get() { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..7a4582ace686897b291f71b50b1ac4cbe1744239 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js new file mode 100644 index 0000000000000000000000000000000000000000..c2eea59d087389ab4a0f1be9ede38b7b2ba4595a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..7ade577b256b25919a4d06a8d432507daef8d3ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..4c69fc39e74c2e0858b85333753db64f58a1a5ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..1ef91d64c80e220e599881771a9bd231879a538f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..24cbcedca58c8ad42d50498a9ffa3241fc85c16a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..390bf8918f4d42be870e23ff3da4ba2ed8d0d68d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..125bc58f79fa0bd952c39bafd8949c69eaf3c780 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..6b47ff517535a6d8c00d6afaff55b0332f825c9c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js new file mode 100644 index 0000000000000000000000000000000000000000..7c522d97a116ac03324325fc8d847ee628ed3cc8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..99d615e096c5e176d7a97cb25f17862a317a970d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..fd052157d4400d572c97905c9b077a8b26dff0d5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..f12212ea3d678e87ae64809b79bbbd98c23e6f50 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..b36324c2aa3faa177230ac9916f02e5fff0a6cd3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..6421c5d5a08e42325718a2caad1f47154eff9de9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..3da8673a5cdf3c408c8ae00fad6aed9777d2ae69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..6e652346d42fbfa5194e33196336372799c568cd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,18 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c25659a79ac408f2ceb0da0a919ddebd0a93eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..382e5d795e1aea61202b73dbc0827b259c4b1237 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..09063b860499e6a7cf4b374be124df5dded05457 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..95ea87991ea56d596b4612d4d063f45906b13c12 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..e87fe317d70a00942dd870c8c1c9155b517aa957 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1db6f6d25b2b6a79d6c650cac2fad395408e1ac2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d1992614bb9acf0470614818f05340647f9c04 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js @@ -0,0 +1,4 @@ +import crypto from 'crypto'; +export default { + randomUUID: crypto.randomUUID +}; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..6421c5d5a08e42325718a2caad1f47154eff9de9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..3da8673a5cdf3c408c8ae00fad6aed9777d2ae69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..80062449a297eb936b592ee631bcec8f273256c9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..e23850b441a0c0d52d0d0aa75ed49cf0b88cd72b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..a6e4c8864ddaf1a1bd9f36839a7975bef7822698 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..09063b860499e6a7cf4b374be124df5dded05457 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..95ea87991ea56d596b4612d4d063f45906b13c12 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..e87fe317d70a00942dd870c8c1c9155b517aa957 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..f1cdc7af49bcfc2a66fb1efb3532095e85ce8415 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000000000000000000000000000000000000..936307630f5ddb07ffdb28e5d343ae12f5e84026 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..824d48167a980e1ea70732421b05f66c8622a12f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js new file mode 100644 index 0000000000000000000000000000000000000000..de80469138d0df75c2f8886e69841a5bbc3e5e1f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..4c69fc39e74c2e0858b85333753db64f58a1a5ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..390bf8918f4d42be870e23ff3da4ba2ed8d0d68d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..99d615e096c5e176d7a97cb25f17862a317a970d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..fd052157d4400d572c97905c9b077a8b26dff0d5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js new file mode 100644 index 0000000000000000000000000000000000000000..f63af01ad44a4433ed1240abd2cc318ef28b47b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..61ece8cc92afb41fdb1552ec1f72ac147b9eaceb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md @@ -0,0 +1,23 @@ +(MIT) + +Original code Copyright Julian Gruber + +Port to TypeScript Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/README.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed10c70aab6f52ffef4df2d0a1c19412febb949e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/README.md @@ -0,0 +1,60 @@ +# @isaacs/balanced-match + +A hybrid CJS/ESM TypeScript fork of +[balanced-match](http://npm.im/balanced-match). + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![CI](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +import { balanced } from '@isaacs/balanced-match' + +console.log(balanced('{', '}', 'pre{in{nested}}post')) +console.log(balanced('{', '}', 'pre{first}between{second}post')) +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')) +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### const m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +- **start** the index of the first match of `a` +- **end** the index of the matching `b` +- **pre** the preamble, `a` and `b` not included +- **body** the match, `a` and `b` not included +- **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### const r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6306762c77d77b909214a5d7af014b2eb156bbb3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0c9014bac153187d5b0e3d1d214a5d1c71eefd32 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.range = exports.balanced = void 0; +const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +exports.balanced = balanced; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i === ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } + else if (begs.length === 1) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +exports.range = range; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b476cae229324756c8359ea6545e7494f13e63d7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,I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egExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49296e6af443c4c424844aa2c73081c3e34b8c8c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/balanced-match/package.json @@ -0,0 +1,79 @@ +{ + "name": "@isaacs/balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "4.0.1", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/balanced-match.git" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46e7b75c91ced041ae473299398af2b0472dc352 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright Julian Gruber + +TypeScript port Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..27f432d98dd6c9c8749e4d0b0b1e30740330701c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAwEA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,YAgBjC"} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..99cee69d560e24a30934a93db3c116532e257417 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js @@ -0,0 +1,196 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.expand = expand; +const balanced_match_1 = require("@isaacs/balanced-match"); +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6c3f6c4c12190b032384b7ddb291c3c279339364 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAwEA,wBAgBC;AAxFD,2DAAiD;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,GAAG,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;AACnD,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,WAAW,GAAG,MAAM,CAAA;A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ACtC,IAAI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ebb88ed4117c87e40d30ee9418c9b2278435de1c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js @@ -0,0 +1,193 @@ +import { balanced } from '@isaacs/balanced-match'; +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = balanced('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +export function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = balanced('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..85c33de61a809638b528c565e532fec712531e6b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,GAAG,IAAI,MAAM,CA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BACrC,MAAM,SAAS,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBACtC,IAAI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cf1035688398b9b4d136c21b9de1e9ace6089b5c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/brace-expansion/package.json @@ -0,0 +1,71 @@ +{ + "name": "@isaacs/brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "5.0.0", + "files": [ + "dist" + ], + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7e27478a3eff8862ca150f10d1b93a5ac866af2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..4567f945e81a73dc2e589f153913910fa2f5fea9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts @@ -0,0 +1,43 @@ +interface UIOptions { + width: number; + wrap?: boolean; + rows?: string[]; +} +interface Column { + text: string; + width?: number; + align?: "right" | "left" | "center"; + padding: number[]; + border?: boolean; +} +interface ColumnArray extends Array { + span: boolean; +} +interface Line { + hidden?: boolean; + text: string; + span?: boolean; +} +declare class UI { + width: number; + wrap: boolean; + rows: ColumnArray[]; + constructor(opts: UIOptions); + span(...args: ColumnArray): void; + resetOutput(): void; + div(...args: (Column | string)[]): ColumnArray; + private shouldApplyLayoutDSL; + private applyLayoutDSL; + private colFromString; + private measurePadding; + toString(): string; + rowToString(row: ColumnArray, lines: Line[]): Line[]; + // if the full 'source' can render in + // the target line, do so. + private renderInline; + private rasterize; + private negatePadding; + private columnWidths; +} +declare function ui(opts: UIOptions): UI; +export { ui as default }; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/index.mjs b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5177519af372221f252cda2d75ac66385f44f753 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@isaacs/cliui/index.mjs @@ -0,0 +1,14 @@ +// Bootstrap cliui with ESM dependencies: +import { cliui } from './build/lib/index.js' + +import stringWidth from 'string-width' +import stripAnsi from 'strip-ansi' +import wrap from 'wrap-ansi' + +export default function ui (opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }) +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/dist/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..001b3fb74dd272de22456d23dd8a1f5c39289229 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/dist/index.js @@ -0,0 +1,37 @@ +var RGX = /^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/, + SEC = 1e3, + MIN = SEC * 60, + HOUR = MIN * 60, + DAY = HOUR * 24, + YEAR = DAY * 365.25; + +function parse(val) { + var num, arr = val.toLowerCase().match(RGX); + if (arr != null && (num = parseFloat(arr[1]))) { + if (arr[3] != null) return num * SEC; + if (arr[4] != null) return num * MIN; + if (arr[5] != null) return num * HOUR; + if (arr[6] != null) return num * DAY; + if (arr[7] != null) return num * DAY * 7; + if (arr[8] != null) return num * YEAR; + return num; + } +} + +function fmt(val, pfx, str, long) { + var num = (val | 0) === val ? val : ~~(val + 0.5); + return pfx + num + (long ? (' ' + str + (num != 1 ? 's' : '')) : str[0]); +} + +function format(num, long) { + var pfx = num < 0 ? '-' : '', abs = num < 0 ? -num : num; + if (abs < SEC) return num + (long ? ' ms' : 'ms'); + if (abs < MIN) return fmt(abs / SEC, pfx, 'second', long); + if (abs < HOUR) return fmt(abs / MIN, pfx, 'minute', long); + if (abs < DAY) return fmt(abs / HOUR, pfx, 'hour', long); + if (abs < YEAR) return fmt(abs / DAY, pfx, 'day', long); + return fmt(abs / YEAR, pfx, 'year', long); +} + +exports.format = format; +exports.parse = parse; \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c69a704650e6be911eb408611b70a41cc2bd79cb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/index.d.ts @@ -0,0 +1,2 @@ +export function format(millis: number, long?: boolean): string; +export function parse(input: string): number | undefined; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/package.json b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..142a7a933564e154a113b362205e393b198cc8f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@lukeed/ms/package.json @@ -0,0 +1,48 @@ +{ + "umd:name": "ms", + "version": "2.0.2", + "name": "@lukeed/ms", + "repository": "lukeed/ms", + "description": "A tiny (414B) and fast utility to convert milliseconds to and from strings.", + "unpkg": "dist/index.min.js", + "module": "dist/index.mjs", + "main": "dist/index.js", + "types": "index.d.ts", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "build": "bundt", + "test": "uvu -r esm test" + }, + "files": [ + "*.d.ts", + "dist" + ], + "keywords": [ + "ms", + "time", + "format", + "milliseconds", + "convert" + ], + "devDependencies": { + "bundt": "1.1.2", + "esm": "3.2.25", + "uvu": "0.5.1" + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..7360d63274a9a40d2d78e8ff74aa88542bcb803d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing to LLMs + +Thank you for your interest in contributing! Please follow these guidelines to ensure smooth collaboration. + +## Development Environment + +- Node.js 18+ +- Recommended package manager: npm or pnpm +- Recommended editor: VSCode + TypeScript plugin + +## Branch & PR Guidelines + +- Create feature/bugfix branches from the latest `main` branch. +- Each feature/fix should be in a separate branch, avoid mixing unrelated changes. +- PR titles should be concise; descriptions must state the purpose, scope, and testing method. +- Ensure local build and tests pass before submitting a PR. + +## Code Style + +- Strict TypeScript mode. +- 2-space indentation. +- Prefer `@/` alias for imports. +- Keep comments clear and up-to-date. + +## Commit Message Convention + +- feat: new feature +- fix: bug fix +- docs: documentation +- refactor: refactor +- test: test related +- chore: build/deps/chore + +## Testing + +- Add/modify unit tests for new/changed features. +- Run `npm test` to ensure all tests pass. + +## Review Process + +- PRs will be reviewed by maintainers/reviewers. +- Address review comments promptly. +- Only merge after approval. + +## FAQ + +- Path alias not working? Check `tsconfig.json` and ensure your runtime supports it. +- Dependency install failed? Try switching npm/pnpm registry or upgrading Node. +- For other issues, please open an issue. + +--- diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f6558adde591be2fd4f35fce208e45adae447860 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs @@ -0,0 +1,103 @@ +var T=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ee=O((Bf,St)=>{"use strict";var Q=e=>e&&typeof e.message=="string",_e=e=>{if(!e)return;let t=e.cause;if(typeof t=="function"){let r=e.cause();return Q(r)?r:void 0}else return Q(t)?t:void 0},bt=(e,t)=>{if(!Q(e))return"";let r=e.stack||"";if(t.has(e))return r+` +causes have become circular...`;let n=_e(e);return n?(t.add(e),r+` +caused by: `+bt(n,t)):r},Bn=e=>bt(e,new Set),wt=(e,t,r)=>{if(!Q(e))return"";let n=r?"":e.message||"";if(t.has(e))return n+": ...";let i=_e(e);if(i){t.add(e);let o=typeof e.cause=="function";return n+(o?"":": ")+wt(i,t,o)}else return n},In=e=>wt(e,new Set);St.exports={isErrorLike:Q,getErrorCause:_e,stackWithCauses:Bn,messageWithCauses:In}});var Oe=O((If,Et)=>{"use strict";var qn=Symbol("circular-ref-tag"),re=Symbol("pino-raw-err-ref"),_t=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[re]},set:function(e){this[re]=e}}});Object.defineProperty(_t,re,{writable:!0,value:{}});Et.exports={pinoErrProto:_t,pinoErrorSymbols:{seen:qn,rawSymbol:re}}});var vt=O((qf,xt)=>{"use strict";xt.exports=ve;var{messageWithCauses:Cn,stackWithCauses:Nn,isErrorLike:Ot}=Ee(),{pinoErrProto:Dn,pinoErrorSymbols:Pn}=Oe(),{seen:xe}=Pn,{toString:zn}=Object.prototype;function ve(e){if(!Ot(e))return e;e[xe]=void 0;let t=Object.create(Dn);t.type=zn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=Cn(e),t.stack=Nn(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>ve(r)));for(let r in e)if(t[r]===void 0){let n=e[r];Ot(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,xe)&&(t[r]=ve(n)):t[r]=n}return delete e[xe],t.raw=e,t}});var $t=O((Cf,Lt)=>{"use strict";Lt.exports=ie;var{isErrorLike:Le}=Ee(),{pinoErrProto:Wn,pinoErrorSymbols:Mn}=Oe(),{seen:ne}=Mn,{toString:Fn}=Object.prototype;function ie(e){if(!Le(e))return e;e[ne]=void 0;let t=Object.create(Wn);t.type=Fn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>ie(r))),Le(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,ne)&&(t.cause=ie(e.cause));for(let r in e)if(t[r]===void 0){let n=e[r];Le(n)?Object.prototype.hasOwnProperty.call(n,ne)||(t[r]=ie(n)):t[r]=n}return delete e[ne],t.raw=e,t}});var kt=O((Nf,Tt)=>{"use strict";Tt.exports={mapHttpRequest:Vn,reqSerializer:jt};var $e=Symbol("pino-raw-req-ref"),At=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[$e]},set:function(e){this[$e]=e}}});Object.defineProperty(At,$e,{writable:!0,value:{}});function jt(e){let t=e.info||e.socket,r=Object.create(At);if(r.id=typeof e.id=="function"?e.id():e.id||(e.info?e.info.id:void 0),r.method=e.method,e.originalUrl)r.url=e.originalUrl;else{let n=e.path;r.url=typeof n=="string"?n:e.url?e.url.path||e.url:void 0}return e.query&&(r.query=e.query),e.params&&(r.params=e.params),r.headers=e.headers,r.remoteAddress=t&&t.remoteAddress,r.remotePort=t&&t.remotePort,r.raw=e.raw||e,r}function Vn(e){return{req:jt(e)}}});var qt=O((Df,It)=>{"use strict";It.exports={mapHttpResponse:Kn,resSerializer:Bt};var Ae=Symbol("pino-raw-res-ref"),Rt=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ae]},set:function(e){this[Ae]=e}}});Object.defineProperty(Rt,Ae,{writable:!0,value:{}});function Bt(e){let t=Object.create(Rt);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function Kn(e){return{res:Bt(e)}}});var Te=O((Pf,Ct)=>{"use strict";var je=vt(),Jn=$t(),se=kt(),oe=qt();Ct.exports={err:je,errWithCause:Jn,mapHttpRequest:se.mapHttpRequest,mapHttpResponse:oe.mapHttpResponse,req:se.reqSerializer,res:oe.resSerializer,wrapErrorSerializer:function(t){return t===je?t:function(n){return t(je(n))}},wrapRequestSerializer:function(t){return t===se.reqSerializer?t:function(n){return t(se.reqSerializer(n))}},wrapResponseSerializer:function(t){return t===oe.resSerializer?t:function(n){return t(oe.resSerializer(n))}}}});var ke=O((zf,Nt)=>{"use strict";function Un(e,t){return t}Nt.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=Un;let r=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(r))return;let n=r.slice(2),i=[];for(let o of n)o&&i.push(o.getFileName());return i}});var Pt=O((Wf,Dt)=>{"use strict";Dt.exports=Gn;function Gn(e={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:r=n=>`fast-redact \u2013 Invalid path (${n})`}=e;return function({paths:i}){i.forEach(o=>{if(typeof o!="string")throw Error(t());try{if(/〇/.test(o))throw Error();let f=(o[0]==="["?"":".")+o.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(f)||/\/\*/.test(f))throw Error();Function(` + 'use strict' + const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); + const \u3007 = null; + o${f} + if ([o${f}].length !== 1) throw Error()`)()}catch{throw Error(r(o))}})}}});var le=O((Mf,zt)=>{"use strict";zt.exports=/[^.[\]]+|\[((?:.)*?)\]/g});var Mt=O((Ff,Wt)=>{"use strict";var Hn=le();Wt.exports=Xn;function Xn({paths:e}){let t=[];var r=0;let n=e.reduce(function(i,o,f){var u=o.match(Hn).map(h=>h.replace(/'|"|`/g,""));let d=o[0]==="[";u=u.map(h=>h[0]==="["?h.substr(1,h.length-2):h);let y=u.indexOf("*");if(y>-1){let h=u.slice(0,y),l=h.join("."),p=u.slice(y+1,u.length),c=p.length>0;r++,t.push({before:h,beforeStr:l,after:p,nested:c})}else i[o]={path:u,val:void 0,precensored:!1,circle:"",escPath:JSON.stringify(o),leadingBracket:d};return i},{});return{wildcards:t,wcLen:r,secret:n}}});var Vt=O((Vf,Ft)=>{"use strict";var Yn=le();Ft.exports=Qn;function Qn({secret:e,serialize:t,wcLen:r,strict:n,isCensorFct:i,censorFctTakesPath:o},f){let u=Function("o",` + if (typeof o !== 'object' || o == null) { + ${ri(n,t)} + } + const { censor, secret } = this + const originalSecret = {} + const secretKeys = Object.keys(secret) + for (var i = 0; i < secretKeys.length; i++) { + originalSecret[secretKeys[i]] = secret[secretKeys[i]] + } + + ${Zn(e,i,o)} + this.compileRestore() + ${ei(r>0,i,o)} + this.secret = originalSecret + ${ti(t)} + `).bind(f);return u.state=f,t===!1&&(u.restore=d=>f.restore(d)),u}function Zn(e,t,r){return Object.keys(e).map(n=>{let{escPath:i,leadingBracket:o,path:f}=e[n],u=o?1:0,d=o?"":".",y=[];for(var h;(h=Yn.exec(n))!==null;){let[,s]=h,{index:g,input:m}=h;g>u&&y.push(m.substring(0,g-(s?0:1)))}var l=y.map(s=>`o${d}${s}`).join(" && ");l.length===0?l+=`o${d}${n} != null`:l+=` && o${d}${n} != null`;let p=` + switch (true) { + ${y.reverse().map(s=>` + case o${d}${s} === censor: + secret[${i}].circle = ${JSON.stringify(s)} + break + `).join(` +`)} + } + `,c=r?`val, ${JSON.stringify(f)}`:"val";return` + if (${l}) { + const val = o${d}${n} + if (val === censor) { + secret[${i}].precensored = true + } else { + secret[${i}].val = val + o${d}${n} = ${t?`censor(${c})`:"censor"} + ${p} + } + } + `}).join(` +`)}function ei(e,t,r){return e===!0?` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${t}, ${r}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${t}, ${r}) + } + } + `:""}function ti(e){return e===!1?"return o":` + var s = this.serialize(o) + this.restore(o) + return s + `}function ri(e,t){return e===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var Be=O((Kf,Ut)=>{"use strict";Ut.exports={groupRedact:ii,groupRestore:ni,nestedRedact:oi,nestedRestore:si};function ni({keys:e,values:t,target:r}){if(r==null||typeof r=="string")return;let n=e.length;for(var i=0;i0;f--)o=o[n[f]];o[n[0]]=i}}function oi(e,t,r,n,i,o,f){let u=Kt(t,r);if(u==null)return;let d=Object.keys(u),y=d.length;for(var h=0;h{"use strict";var{groupRestore:ui,nestedRestore:ci}=Be();Gt.exports=ai;function ai(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:r}=this,n=Object.keys(t),i=hi(t,n),o=r>0,f=o?{secret:t,groupRestore:ui,nestedRestore:ci}:{secret:t};this.restore=Function("o",di(i,n,o)).bind(f),this.restore.state=f}}function hi(e,t){return t.map(r=>{let{circle:n,escPath:i,leadingBracket:o}=e[r],u=n?`o.${n} = secret[${i}].val`:`o${o?"":"."}${r} = secret[${i}].val`,d=`secret[${i}].val = undefined`;return` + if (secret[${i}].val !== undefined) { + try { ${u} } catch (e) {} + ${d} + } + `}).join("")}function di(e,t,r){return` + const secret = this.secret + ${r===!0?` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${t.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o) { + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + } + `:""} + ${e} + return o + `}});var Yt=O((Uf,Xt)=>{"use strict";Xt.exports=yi;function yi(e){let{secret:t,censor:r,compileRestore:n,serialize:i,groupRedact:o,nestedRedact:f,wildcards:u,wcLen:d}=e,y=[{secret:t,censor:r,compileRestore:n}];return i!==!1&&y.push({serialize:i}),d>0&&y.push({groupRedact:o,nestedRedact:f,wildcards:u,wcLen:d}),Object.assign(...y)}});var er=O((Gf,Zt)=>{"use strict";var Qt=Pt(),mi=Mt(),gi=Vt(),pi=Ht(),{groupRedact:bi,nestedRedact:wi}=Be(),Si=Yt(),_i=le(),Ei=Qt(),Ie=e=>e;Ie.restore=Ie;var Oi="[REDACTED]";qe.rx=_i;qe.validator=Qt;Zt.exports=qe;function qe(e={}){let t=Array.from(new Set(e.paths||[])),r="serialize"in e&&(e.serialize===!1||typeof e.serialize=="function")?e.serialize:JSON.stringify,n=e.remove;if(n===!0&&r!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let i=n===!0?void 0:"censor"in e?e.censor:Oi,o=typeof i=="function",f=o&&i.length>1;if(t.length===0)return r||Ie;Ei({paths:t,serialize:r,censor:i});let{wildcards:u,wcLen:d,secret:y}=mi({paths:t,censor:i}),h=pi(),l="strict"in e?e.strict:!0;return gi({secret:y,wcLen:d,serialize:r,strict:l,isCensorFct:o,censorFctTakesPath:f},Si({secret:y,censor:i,compileRestore:h,serialize:r,groupRedact:bi,nestedRedact:wi,wildcards:u,wcLen:d}))}});var H=O((Hf,tr)=>{"use strict";var xi=Symbol("pino.setLevel"),vi=Symbol("pino.getLevel"),Li=Symbol("pino.levelVal"),$i=Symbol("pino.levelComp"),Ai=Symbol("pino.useLevelLabels"),ji=Symbol("pino.useOnlyCustomLevels"),Ti=Symbol("pino.mixin"),ki=Symbol("pino.lsCache"),Ri=Symbol("pino.chindings"),Bi=Symbol("pino.asJson"),Ii=Symbol("pino.write"),qi=Symbol("pino.redactFmt"),Ci=Symbol("pino.time"),Ni=Symbol("pino.timeSliceIndex"),Di=Symbol("pino.stream"),Pi=Symbol("pino.stringify"),zi=Symbol("pino.stringifySafe"),Wi=Symbol("pino.stringifiers"),Mi=Symbol("pino.end"),Fi=Symbol("pino.formatOpts"),Vi=Symbol("pino.messageKey"),Ki=Symbol("pino.errorKey"),Ji=Symbol("pino.nestedKey"),Ui=Symbol("pino.nestedKeyStr"),Gi=Symbol("pino.mixinMergeStrategy"),Hi=Symbol("pino.msgPrefix"),Xi=Symbol("pino.wildcardFirst"),Yi=Symbol.for("pino.serializers"),Qi=Symbol.for("pino.formatters"),Zi=Symbol.for("pino.hooks"),es=Symbol.for("pino.metadata");tr.exports={setLevelSym:xi,getLevelSym:vi,levelValSym:Li,levelCompSym:$i,useLevelLabelsSym:Ai,mixinSym:Ti,lsCacheSym:ki,chindingsSym:Ri,asJsonSym:Bi,writeSym:Ii,serializersSym:Yi,redactFmtSym:qi,timeSym:Ci,timeSliceIndexSym:Ni,streamSym:Di,stringifySym:Pi,stringifySafeSym:zi,stringifiersSym:Wi,endSym:Mi,formatOptsSym:Fi,messageKeySym:Vi,errorKeySym:Ki,nestedKeySym:Ji,wildcardFirstSym:Xi,needsMetadataGsym:es,useOnlyCustomLevelsSym:ji,formattersSym:Qi,hooksSym:Zi,nestedKeyStrSym:Ui,mixinMergeStrategySym:Gi,msgPrefixSym:Hi}});var De=O((Xf,sr)=>{"use strict";var Ne=er(),{redactFmtSym:ts,wildcardFirstSym:fe}=H(),{rx:Ce,validator:rs}=Ne,rr=rs({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:e=>`pino \u2013 redact paths array contains an invalid path (${e})`}),nr="[Redacted]",ir=!1;function ns(e,t){let{paths:r,censor:n}=is(e),i=r.reduce((u,d)=>{Ce.lastIndex=0;let y=Ce.exec(d),h=Ce.exec(d),l=y[1]!==void 0?y[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):y[0];if(l==="*"&&(l=fe),h===null)return u[l]=null,u;if(u[l]===null)return u;let{index:p}=h,c=`${d.substr(p,d.length-1)}`;return u[l]=u[l]||[],l!==fe&&u[l].length===0&&u[l].push(...u[fe]||[]),l===fe&&Object.keys(u).forEach(function(s){u[s]&&u[s].push(c)}),u[l].push(c),u},{}),o={[ts]:Ne({paths:r,censor:n,serialize:t,strict:ir})},f=(...u)=>t(typeof n=="function"?n(...u):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((u,d)=>{if(i[d]===null)u[d]=y=>f(y,[d]);else{let y=typeof n=="function"?(h,l)=>n(h,[d,...l]):n;u[d]=Ne({paths:i[d],censor:y,serialize:t,strict:ir})}return u},o)}function is(e){if(Array.isArray(e))return e={paths:e,censor:nr},rr(e),e;let{paths:t,censor:r=nr,remove:n}=e;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),rr({paths:t,censor:r}),{paths:t,censor:r}}sr.exports=ns});var lr=O((Yf,or)=>{"use strict";var ss=()=>"",os=()=>`,"time":${Date.now()}`,ls=()=>`,"time":${Math.round(Date.now()/1e3)}`,fs=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;or.exports={nullTime:ss,epochTime:os,unixTime:ls,isoTime:fs}});var ur=O((Qf,fr)=>{"use strict";function us(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}fr.exports=cs;function cs(e,t,r){var n=r&&r.stringify||us,i=1;if(typeof e=="object"&&e!==null){var o=t.length+i;if(o===1)return e;var f=new Array(o);f[0]=n(e);for(var u=1;u-1?l:0,e.charCodeAt(c+1)){case 100:case 102:if(h>=d||t[h]==null)break;l=d||t[h]==null)break;l=d||t[h]===void 0)break;l",l=c+2,c++;break}y+=n(t[h]),l=c+2,c++;break;case 115:if(h>=d)break;l{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(r))},e=new Int32Array(new SharedArrayBuffer(4));Pe.exports=t}else{let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););};Pe.exports=e}});var pr=O((eu,gr)=>{"use strict";var j=T("fs"),as=T("events"),hs=T("util").inherits,cr=T("path"),Me=ze(),ds=T("assert"),ue=100,ce=Buffer.allocUnsafe(0),ys=16*1024,ar="buffer",hr="utf8",[ms,gs]=(process.versions.node||"0.0").split(".").map(Number),ps=ms>=22&&gs>=7;function dr(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(o,f){if(o){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",o)}):t.emit("error",o);return}let u=t._reopening;t.fd=f,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():u&&process.nextTick(()=>t.emit("drain")))}let n=t.append?"a":"w",i=t.mode;if(t.sync)try{t.mkdir&&j.mkdirSync(cr.dirname(e),{recursive:!0});let o=j.openSync(e,n,i);r(null,o)}catch(o){throw r(o),o}else t.mkdir?j.mkdir(cr.dirname(e),{recursive:!0},o=>{if(o)return r(o);j.open(e,n,i,r)}):j.open(e,n,i,r)}function N(e){if(!(this instanceof N))return new N(e);let{fd:t,dest:r,minLength:n,maxLength:i,maxWrite:o,periodicFlush:f,sync:u,append:d=!0,mkdir:y,retryEAGAIN:h,fsync:l,contentMode:p,mode:c}=e||{};t=t||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=i||0,this.maxWrite=o||ys,this._periodicFlush=f||0,this._periodicFlushTimer=void 0,this.sync=u||!1,this.writable=!0,this._fsync=l||!1,this.append=d||!1,this.mode=c,this.retryEAGAIN=h||(()=>!0),this.mkdir=y||!1;let s,g;if(p===ar)this._writingBuf=ce,this.write=Ss,this.flush=Es,this.flushSync=xs,this._actualWrite=Ls,s=()=>j.writeSync(this.fd,this._writingBuf),g=()=>j.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===hr)this._writingBuf="",this.write=ws,this.flush=_s,this.flushSync=Os,this._actualWrite=vs,s=()=>j.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>j.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${hr}" and "${ar}", but passed ${p}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")dr(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,S)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Me(ue),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(g,ue);else this._writing=!1,this.emit("error",m);return}this.emit("write",S);let b=We(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let _=s(),x=We(this._writingBuf,this._len,_);this._len=x.len,this._writingBuf=x.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&j.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,ae(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(bs,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function We(e,t,r){return typeof e=="string"&&Buffer.byteLength(e)!==r&&(r=Buffer.from(e).subarray(0,r).toString().length),t=Math.max(t-r,0),e=e.slice(r),{writingBuf:e,len:t}}function bs(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}hs(N,as);function yr(e,t){return e.length===0?ce:e.length===1?e[0]:Buffer.concat(e,t)}function ws(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let t=this._len+e.length,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?r.push(""+e):r[r.length-1]+=e,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(r.push([e]),n.push(e.length)):(r[r.length-1].push(e),n[n.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{j.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",r)},r=n=>{this._flushPending=!1,e(n),this.off("drain",t)};this.once("drain",t),this.once("error",r)}function _s(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&mr.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Es(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&mr.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}N.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&j.close(t,r=>{if(r)return this.emit("error",r)})}),dr(this.file,this)};N.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():ae(this)))};function Os(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let t=j.writeSync(this.fd,e,"utf8"),r=We(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Me(ue)}}try{j.fsyncSync(this.fd)}catch{}}function xs(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=ce);let e=ce;for(;this._bufs.length||e.length;){e.length<=0&&(e=yr(this._bufs[0],this._lens[0]));try{let t=j.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Me(ue)}}}N.prototype.destroy=function(){this.destroyed||ae(this)};function vs(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let t=j.writeSync(this.fd,this._writingBuf,"utf8");e(null,t)}catch(t){e(t)}else j.write(this.fd,this._writingBuf,"utf8",e)}function Ls(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:yr(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=j.writeSync(this.fd,this._writingBuf);e(null,t)}catch(t){e(t)}else ps&&(this._writingBuf=Buffer.from(this._writingBuf)),j.write(this.fd,this._writingBuf,e)}function ae(e){if(e.fd===-1){e.once("ready",ae.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],ds(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{j.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?j.close(e.fd,r):r()}function r(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}N.SonicBoom=N;N.default=N;gr.exports=N});var Fe=O((tu,Er)=>{"use strict";var D={exit:[],beforeExit:[]},br={exit:js,beforeExit:Ts},X;function $s(){X===void 0&&(X=new FinalizationRegistry(ks))}function As(e){D[e].length>0||process.on(e,br[e])}function wr(e){D[e].length>0||(process.removeListener(e,br[e]),D.exit.length===0&&D.beforeExit.length===0&&(X=void 0))}function js(){Sr("exit")}function Ts(){Sr("beforeExit")}function Sr(e){for(let t of D[e]){let r=t.deref(),n=t.fn;r!==void 0&&n(r,e)}D[e]=[]}function ks(e){for(let t of["exit","beforeExit"]){let r=D[t].indexOf(e);D[t].splice(r,r+1),wr(t)}}function _r(e,t,r){if(t===void 0)throw new Error("the object can't be undefined");As(e);let n=new WeakRef(t);n.fn=r,$s(),X.register(t,n),D[e].push(n)}function Rs(e,t){_r("exit",e,t)}function Bs(e,t){_r("beforeExit",e,t)}function Is(e){if(X!==void 0){X.unregister(e);for(let t of["exit","beforeExit"])D[t]=D[t].filter(r=>{let n=r.deref();return n&&n!==e}),wr(t)}}Er.exports={register:Rs,registerBeforeExit:Bs,unregister:Is}});var Or=O((ru,qs)=>{qs.exports={name:"thread-stream",version:"3.1.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var vr=O((nu,xr)=>{"use strict";function Cs(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f===r){i(null,"ok");return}let u=f,d=y=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{u=f,f=Atomics.load(e,t),f===u?d(y>=1e3?1e3:y*2):f===r?i(null,"ok"):i(null,"not-equal")},y)};d(1)}function Ns(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f!==r){i(null,"ok");return}let u=d=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{f=Atomics.load(e,t),f!==r?i(null,"ok"):u(d>=1e3?1e3:d*2)},d)};u(1)}xr.exports={wait:Cs,waitDiff:Ns}});var $r=O((iu,Lr)=>{"use strict";Lr.exports={WRITE_INDEX:4,READ_INDEX:8}});var Rr=O((su,kr)=>{"use strict";var{version:Ds}=Or(),{EventEmitter:Ps}=T("events"),{Worker:zs}=T("worker_threads"),{join:Ws}=T("path"),{pathToFileURL:Ms}=T("url"),{wait:Fs}=vr(),{WRITE_INDEX:B,READ_INDEX:P}=$r(),Vs=T("buffer"),Ks=T("assert"),a=Symbol("kImpl"),Js=Vs.constants.MAX_STRING_LENGTH,ee=class{constructor(t){this._value=t}deref(){return this._value}},de=class{register(){}unregister(){}},Us=process.env.NODE_V8_COVERAGE?de:global.FinalizationRegistry||de,Gs=process.env.NODE_V8_COVERAGE?ee:global.WeakRef||ee,Ar=new Us(e=>{e.exited||e.terminate()});function Hs(e,t){let{filename:r,workerData:n}=t,o=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Ws(__dirname,"lib","worker.js"),f=new zs(o,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Ms(r).href,dataBuf:e[a].dataBuf,stateBuf:e[a].stateBuf,workerData:{$context:{threadStreamVersion:Ds},...n}}});return f.stream=new ee(e),f.on("message",Xs),f.on("exit",Tr),Ar.register(e,f),f}function jr(e){Ks(!e[a].sync),e[a].needDrain&&(e[a].needDrain=!1,e.emit("drain"))}function he(e){let t=Atomics.load(e[a].state,B),r=e[a].data.length-t;if(r>0){if(e[a].buf.length===0){e[a].flushing=!1,e[a].ending?Ge(e):e[a].needDrain&&process.nextTick(jr,e);return}let n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);i<=r?(e[a].buf=e[a].buf.slice(r),ye(e,n,he.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);i>e[a].data.length;)r=r/2,n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);e[a].buf=e[a].buf.slice(r),ye(e,n,he.bind(null,e))}})}else if(r===0){if(t===0&&e[a].buf.length===0)return;e.flush(()=>{Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0),he(e)})}else z(e,new Error("overwritten"))}function Xs(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case"READY":this.stream=new Gs(t),t.flush(()=>{t[a].ready=!0,t.emit("ready")});break;case"ERROR":z(t,e.err);break;case"EVENT":Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case"WARNING":process.emitWarning(e.err);break;default:z(t,new Error("this should not happen: "+e.code))}}function Tr(e){let t=this.stream.deref();t!==void 0&&(Ar.unregister(t),t.worker.exited=!0,t.worker.off("exit",Tr),z(t,e!==0?new Error("the worker thread exited"):null))}var Ke=class extends Ps{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[a]={},this[a].stateBuf=new SharedArrayBuffer(128),this[a].state=new Int32Array(this[a].stateBuf),this[a].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[a].data=Buffer.from(this[a].dataBuf),this[a].sync=t.sync||!1,this[a].ending=!1,this[a].ended=!1,this[a].needDrain=!1,this[a].destroyed=!1,this[a].flushing=!1,this[a].ready=!1,this[a].finished=!1,this[a].errored=null,this[a].closed=!1,this[a].buf="",this.worker=Hs(this,t),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(t){if(this[a].destroyed)return Je(this,new Error("the worker has exited")),!1;if(this[a].ending)return Je(this,new Error("the worker is ending")),!1;if(this[a].flushing&&this[a].buf.length+t.length>=Js)try{Ve(this),this[a].flushing=!0}catch(r){return z(this,r),!1}if(this[a].buf+=t,this[a].sync)try{return Ve(this),!0}catch(r){return z(this,r),!1}return this[a].flushing||(this[a].flushing=!0,setImmediate(he,this)),this[a].needDrain=this[a].data.length-this[a].buf.length-Atomics.load(this[a].state,B)<=0,!this[a].needDrain}end(){this[a].destroyed||(this[a].ending=!0,Ge(this))}flush(t){if(this[a].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let r=Atomics.load(this[a].state,B);Fs(this[a].state,P,r,1/0,(n,i)=>{if(n){z(this,n),process.nextTick(t,n);return}if(i==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[a].destroyed||(Ve(this),Ue(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[a].ready}get destroyed(){return this[a].destroyed}get closed(){return this[a].closed}get writable(){return!this[a].destroyed&&!this[a].ending}get writableEnded(){return this[a].ending}get writableFinished(){return this[a].finished}get writableNeedDrain(){return this[a].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[a].errored}};function Je(e,t){setImmediate(()=>{e.emit("error",t)})}function z(e,t){e[a].destroyed||(e[a].destroyed=!0,t&&(e[a].errored=t,Je(e,t)),e.worker.exited?setImmediate(()=>{e[a].closed=!0,e.emit("close")}):e.worker.terminate().catch(()=>{}).then(()=>{e[a].closed=!0,e.emit("close")}))}function ye(e,t,r){let n=Atomics.load(e[a].state,B),i=Buffer.byteLength(t);return e[a].data.write(t,n),Atomics.store(e[a].state,B,n+i),Atomics.notify(e[a].state,B),r(),!0}function Ge(e){if(!(e[a].ended||!e[a].ending||e[a].flushing)){e[a].ended=!0;try{e.flushSync();let t=Atomics.load(e[a].state,P);Atomics.store(e[a].state,B,-1),Atomics.notify(e[a].state,B);let r=0;for(;t!==-1;){if(Atomics.wait(e[a].state,P,t,1e3),t=Atomics.load(e[a].state,P),t===-2){z(e,new Error("end() failed"));return}if(++r===10){z(e,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{e[a].finished=!0,e.emit("finish")})}catch(t){z(e,t)}}}function Ve(e){let t=()=>{e[a].ending?Ge(e):e[a].needDrain&&process.nextTick(jr,e)};for(e[a].flushing=!1;e[a].buf.length!==0;){let r=Atomics.load(e[a].state,B),n=e[a].data.length-r;if(n===0){Ue(e),Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);continue}else if(n<0)throw new Error("overwritten");let i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);if(o<=n)e[a].buf=e[a].buf.slice(n),ye(e,i,t);else{for(Ue(e),Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);o>e[a].buf.length;)n=n/2,i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);e[a].buf=e[a].buf.slice(n),ye(e,i,t)}}}function Ue(e){if(e[a].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(e[a].state,B),r=0;for(;;){let n=Atomics.load(e[a].state,P);if(n===-2)throw Error("_flushSync failed");if(n!==t)Atomics.wait(e[a].state,P,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}kr.exports=Ke});var Ye=O((ou,Br)=>{"use strict";var{createRequire:Ys}=T("module"),Qs=ke(),{join:He,isAbsolute:Zs,sep:eo}=T("node:path"),to=ze(),Xe=Fe(),ro=Rr();function no(e){Xe.register(e,so),Xe.registerBeforeExit(e,oo),e.on("close",function(){Xe.unregister(e)})}function io(e,t,r,n){let i=new ro({filename:e,workerData:t,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",f)}),process.on("exit",f);function o(){process.removeListener("exit",f),i.unref(),r.autoEnd!==!1&&no(i)}function f(){i.closed||(i.flushSync(),to(100),i.end())}return i}function so(e){e.ref(),e.flushSync(),e.end(),e.once("close",function(){e.unref()})}function oo(e){e.flushSync()}function lo(e){let{pipeline:t,targets:r,levels:n,dedupe:i,worker:o={},caller:f=Qs(),sync:u=!1}=e,d={...e.options},y=typeof f=="string"?[f]:f,h="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},l=e.target;if(l&&r)throw new Error("only one of target or targets can be specified");return r?(l=h["pino-worker"]||He(__dirname,"worker.js"),d.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),d.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(s=>({...s,level:c.level,target:p(s.target)})))):t&&(l=h["pino-worker"]||He(__dirname,"worker.js"),d.pipelines=[t.map(c=>({...c,target:p(c.target)}))]),n&&(d.levels=n),i&&(d.dedupe=i),d.pinoWillSendConfig=!0,io(p(l),d,o,u);function p(c){if(c=h[c]||c,Zs(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return He(__dirname,"..","file.js");let s;for(let g of y)try{let m=g==="node:repl"?process.cwd()+eo:g;s=Ys(m).resolve(c);break}catch{continue}if(!s)throw new Error(`unable to determine transport target for "${c}"`);return s}}Br.exports=lo});var pe=O((lu,Vr)=>{"use strict";var Ir=ur(),{mapHttpRequest:fo,mapHttpResponse:uo}=Te(),Ze=pr(),qr=Fe(),{lsCacheSym:co,chindingsSym:Dr,writeSym:Cr,serializersSym:Pr,formatOptsSym:Nr,endSym:ao,stringifiersSym:zr,stringifySym:Wr,stringifySafeSym:et,wildcardFirstSym:Mr,nestedKeySym:ho,formattersSym:Fr,messageKeySym:yo,errorKeySym:mo,nestedKeyStrSym:go,msgPrefixSym:me}=H(),{isMainThread:po}=T("worker_threads"),bo=Ye();function Y(){}function wo(e,t){if(!t)return r;return function(...i){t.call(this,i,r,e)};function r(n,...i){if(typeof n=="object"){let o=n;n!==null&&(n.method&&n.headers&&n.socket?n=fo(n):typeof n.setHeader=="function"&&(n=uo(n)));let f;o===null&&i.length===0?f=[null]:(o=i.shift(),f=i),typeof this[me]=="string"&&o!==void 0&&o!==null&&(o=this[me]+o),this[Cr](n,Ir(o,f,this[Nr]),e)}else{let o=n===void 0?i.shift():n;typeof this[me]=="string"&&o!==void 0&&o!==null&&(o=this[me]+o),this[Cr](null,Ir(o,i,this[Nr]),e)}}}function Qe(e){let t="",r=0,n=!1,i=255,o=e.length;if(o>100)return JSON.stringify(e);for(var f=0;f=32;f++)i=e.charCodeAt(f),(i===34||i===92)&&(t+=e.slice(r,f)+"\\",r=f,n=!0);return n?t+=e.slice(r):t=e,i<32?JSON.stringify(e):'"'+t+'"'}function So(e,t,r,n){let i=this[Wr],o=this[et],f=this[zr],u=this[ao],d=this[Dr],y=this[Pr],h=this[Fr],l=this[yo],p=this[mo],c=this[co][r]+n;c=c+d;let s;h.log&&(e=h.log(e));let g=f[Mr],m="";for(let b in e)if(s=e[b],Object.prototype.hasOwnProperty.call(e,b)&&s!==void 0){y[b]?s=y[b](s):b===p&&y.err&&(s=y.err(s));let w=f[b]||g;switch(typeof s){case"undefined":case"function":continue;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":w&&(s=w(s));break;case"string":s=(w||Qe)(s);break;default:s=(w||i)(s,o)}if(s===void 0)continue;let _=Qe(b);m+=","+_+":"+s}let S="";if(t!==void 0){s=y[l]?y[l](t):t;let b=f[l]||g;switch(typeof s){case"function":break;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":b&&(s=b(s)),S=',"'+l+'":'+s;break;case"string":s=(b||Qe)(s),S=',"'+l+'":'+s;break;default:s=(b||i)(s,o),S=',"'+l+'":'+s}}return this[ho]&&m?c+this[go]+m.slice(1)+"}"+S+u:c+m+S+u}function _o(e,t){let r,n=e[Dr],i=e[Wr],o=e[et],f=e[zr],u=f[Mr],d=e[Pr],y=e[Fr].bindings;t=y(t);for(let h in t)if(r=t[h],(h!=="level"&&h!=="serializers"&&h!=="formatters"&&h!=="customLevels"&&t.hasOwnProperty(h)&&r!==void 0)===!0){if(r=d[h]?d[h](r):r,r=(f[h]||u||i)(r,o),r===void 0)continue;n+=',"'+h+'":'+r}return n}function Eo(e){return e.write!==e.constructor.prototype.write}function ge(e){let t=new Ze(e);return t.on("error",r),!e.sync&&po&&(qr.register(t,Oo),t.on("close",function(){qr.unregister(t)})),t;function r(n){if(n.code==="EPIPE"){t.write=Y,t.end=Y,t.flushSync=Y,t.destroy=Y;return}t.removeListener("error",r),t.emit("error",n)}}function Oo(e,t){e.destroyed||(t==="beforeExit"?(e.flush(),e.on("drain",function(){e.end()})):e.flushSync())}function xo(e){return function(r,n,i={},o){if(typeof i=="string")o=ge({dest:i}),i={};else if(typeof o=="string"){if(i&&i.transport)throw Error("only one of option.transport or stream can be specified");o=ge({dest:o})}else if(i instanceof Ze||i.writable||i._writableState)o=i,i={};else if(i.transport){if(i.transport instanceof Ze||i.transport.writable||i.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(i.transport.targets&&i.transport.targets.length&&i.formatters&&typeof i.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let d;i.customLevels&&(d=i.useOnlyCustomLevels?i.customLevels:Object.assign({},i.levels,i.customLevels)),o=bo({caller:n,...i.transport,levels:d})}if(i=Object.assign({},e,i),i.serializers=Object.assign({},e.serializers,i.serializers),i.formatters=Object.assign({},e.formatters,i.formatters),i.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:f,onChild:u}=i;return f===!1&&(i.level="silent"),u||(i.onChild=Y),o||(Eo(process.stdout)?o=process.stdout:o=ge({fd:process.stdout.fd||1})),{opts:i,stream:o}}}function vo(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[et])(e)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Lo(e,t,r){return{level:e,bindings:t,log:r}}function $o(e){let t=Number(e);return typeof e=="string"&&Number.isFinite(t)?t:e===void 0?1:e}Vr.exports={noop:Y,buildSafeSonicBoom:ge,asChindings:_o,asJson:So,genLog:wo,createArgsNormalizer:xo,stringify:vo,buildFormatters:Lo,normalizeDestFileDescriptor:$o}});var be=O((fu,Kr)=>{var Ao={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},jo={ASC:"ASC",DESC:"DESC"};Kr.exports={DEFAULT_LEVELS:Ao,SORTING_ORDER:jo}});var nt=O((uu,Hr)=>{"use strict";var{lsCacheSym:To,levelValSym:tt,useOnlyCustomLevelsSym:ko,streamSym:Ro,formattersSym:Bo,hooksSym:Io,levelCompSym:Jr}=H(),{noop:qo,genLog:K}=pe(),{DEFAULT_LEVELS:W,SORTING_ORDER:Ur}=be(),Gr={fatal:e=>{let t=K(W.fatal,e);return function(...r){let n=this[Ro];if(t.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:e=>K(W.error,e),warn:e=>K(W.warn,e),info:e=>K(W.info,e),debug:e=>K(W.debug,e),trace:e=>K(W.trace,e)},rt=Object.keys(W).reduce((e,t)=>(e[W[t]]=t,e),{}),Co=Object.keys(rt).reduce((e,t)=>(e[t]='{"level":'+Number(t),e),{});function No(e){let t=e[Bo].level,{labels:r}=e.levels,n={};for(let i in r){let o=t(r[i],Number(i));n[i]=JSON.stringify(o).slice(0,-1)}return e[To]=n,e}function Do(e,t){if(t)return!1;switch(e){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Po(e){let{labels:t,values:r}=this.levels;if(typeof e=="number"){if(t[e]===void 0)throw Error("unknown level value"+e);e=t[e]}if(r[e]===void 0)throw Error("unknown level "+e);let n=this[tt],i=this[tt]=r[e],o=this[ko],f=this[Jr],u=this[Io].logMethod;for(let d in r){if(f(r[d],i)===!1){this[d]=qo;continue}this[d]=Do(d,o)?Gr[d](u):K(r[d],u)}this.emit("level-change",e,i,t[n],n,this)}function zo(e){let{levels:t,levelVal:r}=this;return t&&t.labels?t.labels[r]:""}function Wo(e){let{values:t}=this.levels,r=t[e];return r!==void 0&&this[Jr](r,this[tt])}function Mo(e,t,r){return e===Ur.DESC?t<=r:t>=r}function Fo(e){return typeof e=="string"?Mo.bind(null,e):e}function Vo(e=null,t=!1){let r=e?Object.keys(e).reduce((o,f)=>(o[e[f]]=f,o),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:rt,r),i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:W,e);return{labels:n,values:i}}function Ko(e,t,r){if(typeof e=="number"){if(![].concat(Object.keys(t||{}).map(o=>t[o]),r?[]:Object.keys(rt).map(o=>+o),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:W,t);if(!(e in n))throw Error(`default level:${e} must be included in custom levels`)}function Jo(e,t){let{labels:r,values:n}=e;for(let i in t){if(i in n)throw Error("levels cannot be overridden");if(t[i]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Uo(e){if(typeof e!="function"&&!(typeof e=="string"&&Object.values(Ur).includes(e)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Hr.exports={initialLsCache:Co,genLsCache:No,levelMethods:Gr,getLevel:zo,setLevel:Po,isLevelEnabled:Wo,mappings:Vo,assertNoLevelCollisions:Jo,assertDefaultLevelFound:Ko,genLevelComparison:Fo,assertLevelComparison:Uo}});var it=O((cu,Xr)=>{"use strict";Xr.exports={version:"9.7.0"}});var fn=O((hu,ln)=>{"use strict";var{EventEmitter:Go}=T("node:events"),{lsCacheSym:Ho,levelValSym:Xo,setLevelSym:ot,getLevelSym:Yr,chindingsSym:lt,parsedChindingsSym:Yo,mixinSym:Qo,asJsonSym:rn,writeSym:Zo,mixinMergeStrategySym:el,timeSym:tl,timeSliceIndexSym:rl,streamSym:nn,serializersSym:J,formattersSym:st,errorKeySym:nl,messageKeySym:il,useOnlyCustomLevelsSym:sl,needsMetadataGsym:ol,redactFmtSym:ll,stringifySym:fl,formatOptsSym:ul,stringifiersSym:cl,msgPrefixSym:Qr,hooksSym:al}=H(),{getLevel:hl,setLevel:dl,isLevelEnabled:yl,mappings:ml,initialLsCache:gl,genLsCache:pl,assertNoLevelCollisions:bl}=nt(),{asChindings:sn,asJson:wl,buildFormatters:Zr,stringify:en}=pe(),{version:Sl}=it(),_l=De(),El=class{},on={constructor:El,child:Ol,bindings:xl,setBindings:vl,flush:jl,isLevelEnabled:yl,version:Sl,get level(){return this[Yr]()},set level(e){this[ot](e)},get levelVal(){return this[Xo]},set levelVal(e){throw Error("levelVal is read-only")},[Ho]:gl,[Zo]:$l,[rn]:wl,[Yr]:hl,[ot]:dl};Object.setPrototypeOf(on,Go.prototype);ln.exports=function(){return Object.create(on)};var tn=e=>e;function Ol(e,t){if(!e)throw Error("missing bindings for child Pino");t=t||{};let r=this[J],n=this[st],i=Object.create(this);if(t.hasOwnProperty("serializers")===!0){i[J]=Object.create(null);for(let h in r)i[J][h]=r[h];let d=Object.getOwnPropertySymbols(r);for(var o=0;o{"use strict";var{hasOwnProperty:te}=Object.prototype,G=ct();G.configure=ct;G.stringify=G;G.default=G;at.stringify=G;at.configure=ct;an.exports=G;var Tl=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function F(e){return e.length<5e3&&!Tl.test(e)?`"${e}"`:JSON.stringify(e)}function ft(e,t){if(e.length>200||t)return e.sort(t);for(let r=1;rn;)e[i]=e[i-1],i--;e[i]=n}return e}var kl=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ut(e){return kl.call(e)!==void 0&&e.length!==0}function un(e,t,r){e.length= 1`)}return r===void 0?1/0:r}function U(e){return e===1?"1 item":`${e} items`}function ql(e){let t=new Set;for(let r of e)(typeof r=="string"||typeof r=="number")&&t.add(String(r));return t}function Cl(e){if(te.call(e,"strict")){let t=e.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function ct(e){e={...e};let t=Cl(e);t&&(e.bigint===void 0&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));let r=Rl(e),n=Il(e,"bigint"),i=Bl(e),o=typeof i=="function"?i:void 0,f=cn(e,"maximumDepth"),u=cn(e,"maximumBreadth");function d(c,s,g,m,S,b){let w=s[c];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(c)),w=m.call(s,c,w),typeof w){case"string":return F(w);case"object":{if(w===null)return"null";if(g.indexOf(w)!==-1)return r;let _="",x=",",v=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(fu){let V=w.length-u-1;_+=`${x}"... ${U(V)} not stringified"`}return S!==""&&(_+=` +${v}`),g.pop(),`[${_}]`}let L=Object.keys(w),$=L.length;if($===0)return"{}";if(fu){let k=$-u;_+=`${A}"...":${E}"${U(k)} not stringified"`,A=x}return S!==""&&A.length>1&&(_=` +${b}${_} +${v}`),g.pop(),`{${_}}`}case"number":return isFinite(w)?String(w):t?t(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return t?t(w):void 0}}function y(c,s,g,m,S,b){switch(typeof s=="object"&&s!==null&&typeof s.toJSON=="function"&&(s=s.toJSON(c)),typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(g.indexOf(s)!==-1)return r;let w=b,_="",x=",";if(Array.isArray(s)){if(s.length===0)return"[]";if(fu){let R=s.length-u-1;_+=`${x}"... ${U(R)} not stringified"`}return S!==""&&(_+=` +${w}`),g.pop(),`[${_}]`}g.push(s);let v="";S!==""&&(b+=S,x=`, +${b}`,v=" ");let L="";for(let $ of m){let E=y($,s[$],g,m,S,b);E!==void 0&&(_+=`${L}${F($)}:${v}${E}`,L=x)}return S!==""&&L.length>1&&(_=` +${b}${_} +${w}`),g.pop(),`{${_}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function h(c,s,g,m,S){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(c),typeof s!="object")return h(c,s,g,m,S);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let b=S;if(Array.isArray(s)){if(s.length===0)return"[]";if(fu){let q=s.length-u-1;E+=`${A}"... ${U(q)} not stringified"`}return E+=` +${b}`,g.pop(),`[${E}]`}let w=Object.keys(s),_=w.length;if(_===0)return"{}";if(fu){let E=_-u;v+=`${L}"...": "${U(E)} not stringified"`,L=x}return L!==""&&(v=` +${S}${v} +${b}`),g.pop(),`{${v}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function l(c,s,g){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(c),typeof s!="object")return l(c,s,g);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let m="",S=s.length!==void 0;if(S&&Array.isArray(s)){if(s.length===0)return"[]";if(fu){let E=s.length-u-1;m+=`,"... ${U(E)} not stringified"`}return g.pop(),`[${m}]`}let b=Object.keys(s),w=b.length;if(w===0)return"{}";if(fu){let v=w-u;m+=`${_}"...":"${U(v)} not stringified"`}return g.pop(),`{${m}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function p(c,s,g){if(arguments.length>1){let m="";if(typeof g=="number"?m=" ".repeat(Math.min(g,10)):typeof g=="string"&&(m=g.slice(0,10)),s!=null){if(typeof s=="function")return d("",{"":c},[],s,m,"");if(Array.isArray(s))return y("",c,[],ql(s),m,"")}if(m.length!==0)return h("",c,[],m,"")}return l("",c,[])}return p}});var mn=O((du,yn)=>{"use strict";var ht=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:dn}=be(),Nl=dn.info;function Dl(e,t){let r=0;e=e||[],t=t||{dedupe:!1};let n=Object.create(dn);n.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(l=>{n[l]=t.levels[l]});let i={write:o,add:d,emit:f,flushSync:u,end:y,minLevel:0,streams:[],clone:h,[ht]:!0,streamLevels:n};return Array.isArray(e)?e.forEach(d,i):d.call(i,e),e=null,i;function o(l){let p,c=this.lastLevel,{streams:s}=this,g=0,m;for(let S=zl(s.length,t.dedupe);Ml(S,s.length,t.dedupe);S=Wl(S,t.dedupe))if(p=s[S],p.level<=c){if(g!==0&&g!==p.level)break;if(m=p.stream,m[ht]){let{lastTime:b,lastMsg:w,lastObj:_,lastLogger:x}=this;m.lastLevel=c,m.lastTime=b,m.lastMsg=w,m.lastObj=_,m.lastLogger=x}m.write(l),t.dedupe&&(g=p.level)}else if(!t.dedupe)break}function f(...l){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...l)}function u(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync()}function d(l){if(!l)return i;let p=typeof l.write=="function"||l.stream,c=l.write?l:l.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:s,streamLevels:g}=this,m;typeof l.levelVal=="number"?m=l.levelVal:typeof l.level=="string"?m=g[l.level]:typeof l.level=="number"?m=l.level:m=Nl;let S={stream:c,level:m,levelVal:void 0,id:r++};return s.unshift(S),s.sort(Pl),this.minLevel=s[0].level,i}function y(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync(),l.end()}function h(l){let p=new Array(this.streams.length);for(let c=0;c=0:e{function we(e){try{return T("path").join(`${process.cwd()}${T("path").sep}dist/esm`.replace(/\\/g,"/"),e)}catch{return new Function("p","return new URL(p, import.meta.url).pathname")(e)}}globalThis.__bundlerPathsOverrides={...globalThis.__bundlerPathsOverrides||{},"thread-stream-worker":we("./thread-stream-worker.mjs"),"pino-worker":we("./pino-worker.mjs"),"pino/file":we("./pino-file.mjs"),"pino-roll":we("./pino-roll.mjs")};var Fl=T("node:os"),On=Te(),Vl=ke(),Kl=De(),xn=lr(),Jl=fn(),vn=H(),{configure:Ul}=hn(),{assertDefaultLevelFound:Gl,mappings:Ln,genLsCache:Hl,genLevelComparison:Xl,assertLevelComparison:Yl}=nt(),{DEFAULT_LEVELS:$n,SORTING_ORDER:Ql}=be(),{createArgsNormalizer:Zl,asChindings:ef,buildSafeSonicBoom:gn,buildFormatters:tf,stringify:dt,normalizeDestFileDescriptor:pn,noop:rf}=pe(),{version:nf}=it(),{chindingsSym:bn,redactFmtSym:sf,serializersSym:wn,timeSym:of,timeSliceIndexSym:lf,streamSym:ff,stringifySym:Sn,stringifySafeSym:yt,stringifiersSym:_n,setLevelSym:uf,endSym:cf,formatOptsSym:af,messageKeySym:hf,errorKeySym:df,nestedKeySym:yf,mixinSym:mf,levelCompSym:gf,useOnlyCustomLevelsSym:pf,formattersSym:En,hooksSym:bf,nestedKeyStrSym:wf,mixinMergeStrategySym:Sf,msgPrefixSym:_f}=vn,{epochTime:An,nullTime:Ef}=xn,{pid:Of}=process,xf=Fl.hostname(),vf=On.err,Lf={level:"info",levelComparison:Ql.ASC,levels:$n,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Of,hostname:xf},serializers:Object.assign(Object.create(null),{err:vf}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:An,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},$f=Zl(Lf),Af=Object.assign(Object.create(null),On);function mt(...e){let t={},{opts:r,stream:n}=$f(t,Vl(),...e);r.level&&typeof r.level=="string"&&$n[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:i,crlf:o,serializers:f,timestamp:u,messageKey:d,errorKey:y,nestedKey:h,base:l,name:p,level:c,customLevels:s,levelComparison:g,mixin:m,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:w,hooks:_,depthLimit:x,edgeLimit:v,onChild:L,msgPrefix:$}=r,E=Ul({maximumDepth:x,maximumBreadth:v}),A=tf(w.level,w.bindings,w.log),R=dt.bind({[yt]:E}),k=i?Kl(i,R):{},I=i?{stringify:k[sf]}:{stringify:R},q="}"+(o?`\r +`:` +`),V=ef.bind(null,{[bn]:"",[wn]:f,[_n]:k,[Sn]:dt,[yt]:E,[En]:A}),Se="";l!==null&&(p===void 0?Se=V(l):Se=V(Object.assign({},l,{name:p})));let gt=u instanceof Function?u:u?An:Ef,kn=gt().indexOf(":")+1;if(b&&!s)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(m&&typeof m!="function")throw Error(`Unknown mixin type "${typeof m}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);Gl(c,s,b);let pt=Ln(s,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:pt,messageKey:d,errorKey:y}}),Yl(g);let Rn=Xl(g);return Object.assign(t,{levels:pt,[gf]:Rn,[pf]:b,[ff]:n,[of]:gt,[lf]:kn,[Sn]:dt,[yt]:E,[_n]:k,[cf]:q,[af]:I,[hf]:d,[df]:y,[yf]:h,[wf]:h?`,${JSON.stringify(h)}:{`:"",[wn]:f,[mf]:m,[Sf]:S,[bn]:Se,[En]:A,[bf]:_,silent:rf,onChild:L,[_f]:$}),Object.setPrototypeOf(t,Jl()),Hl(t),t[uf](c),t}C.exports=mt;C.exports.destination=(e=process.stdout.fd)=>typeof e=="object"?(e.dest=pn(e.dest||process.stdout.fd),gn(e)):gn({dest:pn(e),minLength:0});C.exports.transport=Ye();C.exports.multistream=mn();C.exports.levels=Ln();C.exports.stdSerializers=Af;C.exports.stdTimeFunctions=Object.assign({},xn);C.exports.symbols=vn;C.exports.version=nf;C.exports.default=mt;C.exports.pino=mt});var kf=O((mu,Tn)=>{var jf=jn(),{once:Tf}=T("node:events");Tn.exports=async function(e={}){let t=Object.assign({},e,{dest:e.destination||1,sync:!1});delete t.destination;let r=jf.destination(t);return await Tf(r,"ready"),r}});export default kf(); +//# sourceMappingURL=pino-file.mjs.map diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1aad850d10ed4b5db1215fbc28c331fddc1915eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/file.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/esm`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.mjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.mjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.mjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.mjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "'use strict'\n\nconst pino = require('./pino')\nconst { once } = require('node:events')\n\nmodule.exports = async function (opts = {}) {\n const destOpts = Object.assign({}, opts, { dest: opts.destination || 1, sync: false })\n delete destOpts.destination\n const destination = pino.destination(destOpts)\n await once(destination, 'ready')\n return destination\n}\n"], + "mappings": "uTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAIV,IAAME,EAAQF,EAAI,MAGlB,GAAI,OAAOE,GAAU,WAAY,CAE/B,IAAMC,EAAcH,EAAI,MAAM,EAE9B,OAAOD,EAAYI,CAAW,EAC1BA,EACA,MACN,KACE,QAAOJ,EAAYG,CAAK,EACpBA,EACA,MAER,EAUME,GAAmB,CAACJ,EAAKK,IAAS,CACtC,GAAI,CAACN,EAAYC,CAAG,EAAG,MAAO,GAE9B,IAAMM,EAAQN,EAAI,OAAS,GAG3B,GAAIK,EAAK,IAAIL,CAAG,EACd,OAAOM,EAAQ;AAAA,gCAGjB,IAAMJ,EAAQD,GAAcD,CAAG,EAE/B,OAAIE,GACFG,EAAK,IAAIL,CAAG,EACJM,EAAQ;AA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xD,GACR,QAAA2D,EACA,CAACnC,EAAY,EAAGoC,CAClB,CAAC,EAED,OAAO,eAAetB,EAAUtD,GAAM,CAAC,EAEvCK,GAAWiD,CAAQ,EAEnBA,EAAS3B,EAAW,EAAEsC,CAAK,EAEpBX,CACT,CAEA9D,EAAO,QAAU4D,GAEjB5D,EAAO,QAAQ,YAAc,CAACgG,EAAO,QAAQ,OAAO,KAC9C,OAAOA,GAAS,UAClBA,EAAK,KAAOzE,GAA4ByE,EAAK,MAAQ,QAAQ,OAAO,EAAE,EAC/D5E,GAAmB4E,CAAI,GAEvB5E,GAAmB,CAAE,KAAMG,GAA4ByE,CAAI,EAAG,UAAW,CAAE,CAAC,EAIvFhG,EAAO,QAAQ,UAAY,KAC3BA,EAAO,QAAQ,YAAc,KAE7BA,EAAO,QAAQ,OAASY,GAAS,EACjCZ,EAAO,QAAQ,eAAiB2D,GAChC3D,EAAO,QAAQ,iBAAmB,OAAO,OAAO,CAAC,EAAGO,EAAI,EACxDP,EAAO,QAAQ,QAAUS,GACzBT,EAAO,QAAQ,QAAUyB,GAGzBzB,EAAO,QAAQ,QAAU4D,GACzB5D,EAAO,QAAQ,KAAO4D,KCpPtB,IAAAqC,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CAEA,IAAMC,GAAO,KACP,CAAE,KAAAC,EAAK,EAAI,EAAQ,aAAa,EAEtCF,GAAO,QAAU,eAAgBG,EAAO,CAAC,EAAG,CAC1C,IAAMC,EAAW,OAAO,OAAO,CAAC,EAAGD,EAAM,CAAE,KAAMA,EAAK,aAAe,EAAG,KAAM,EAAM,CAAC,EACrF,OAAOC,EAAS,YAChB,IAAMC,EAAcJ,GAAK,YAAYG,CAAQ,EAC7C,aAAMF,GAAKG,EAAa,OAAO,EACxBA,CACT", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "require_file", "__commonJSMin", "exports", "module", "pino", "once", "opts", "destOpts", "destination"] +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..702f301cc8cdc2b0cde32b69e781073d7443342a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/add.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWeekend.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/areIntervalsOverlapping.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/max.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/min.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/clamp.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestIndexTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareDesc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/daysToWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachDayOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachHourOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMinuteOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMonthOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachQuarterOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachYearOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultLocale.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/addLeadingZeros.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/lightFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/formatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/longFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/protectedTokens.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO9075.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISODuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC3339.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC7231.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/fromUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLeapYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeeksInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getOverlappingDaysInIntervals.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeeksInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/interval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intervalToDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isAfter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isBefore.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isEqual.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isExists.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFirstDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFuture.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Setter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/EraParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/utils.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/YearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ExtendedYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/QuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneQuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneMonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DateParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayOfYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneLocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISODayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMMidnightParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayPeriodParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1to12Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0to23Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0To11Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1To24Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MinuteParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/SecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/FractionOfSecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneWithZParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampSecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampMillisecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMatch.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isPast.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWithinInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lightFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/milliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseJSON.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/set.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/sub.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/weeksToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/index.cjs", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/lib/utils.js", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/pino-roll.js"], + "sourcesContent": ["'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "\"use strict\";\nexports.secondsInYear =\n exports.secondsInWeek =\n exports.secondsInQuarter =\n exports.secondsInMonth =\n exports.secondsInMinute =\n exports.secondsInHour =\n exports.secondsInDay =\n exports.quartersInYear =\n exports.monthsInYear =\n exports.monthsInQuarter =\n exports.minutesInYear =\n exports.minutesInMonth =\n exports.minutesInHour =\n exports.minutesInDay =\n exports.minTime =\n exports.millisecondsInWeek =\n exports.millisecondsInSecond =\n exports.millisecondsInMinute =\n exports.millisecondsInHour =\n exports.millisecondsInDay =\n exports.maxTime =\n exports.daysInYear =\n exports.daysInWeek =\n exports.constructFromSymbol =\n void 0; /**\n * @module constants\n * @summary Useful constants\n * @description\n * Collection of useful date constants.\n *\n * The constants could be imported from `date-fns/constants`:\n *\n * ```ts\n * import { maxTime, minTime } from \"date-fns/constants\";\n *\n * function isAllowedTime(time) {\n * return time <= maxTime && time >= minTime;\n * }\n * ```\n */\n\n/**\n * @constant\n * @name daysInWeek\n * @summary Days in 1 week.\n */\nconst daysInWeek = (exports.daysInWeek = 7);\n\n/**\n * @constant\n * @name daysInYear\n * @summary Days in 1 year.\n *\n * @description\n * How many days in a year.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n */\nconst daysInYear = (exports.daysInYear = 365.2425);\n\n/**\n * @constant\n * @name maxTime\n * @summary Maximum allowed time.\n *\n * @example\n * import { maxTime } from \"date-fns/constants\";\n *\n * const isValid = 8640000000000001 <= maxTime;\n * //=> false\n *\n * new Date(8640000000000001);\n * //=> Invalid Date\n */\nconst maxTime = (exports.maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000);\n\n/**\n * @constant\n * @name minTime\n * @summary Minimum allowed time.\n *\n * @example\n * import { minTime } from \"date-fns/constants\";\n *\n * const isValid = -8640000000000001 >= minTime;\n * //=> false\n *\n * new Date(-8640000000000001)\n * //=> Invalid Date\n */\nconst minTime = (exports.minTime = -maxTime);\n\n/**\n * @constant\n * @name millisecondsInWeek\n * @summary Milliseconds in 1 week.\n */\nconst millisecondsInWeek = (exports.millisecondsInWeek = 604800000);\n\n/**\n * @constant\n * @name millisecondsInDay\n * @summary Milliseconds in 1 day.\n */\nconst millisecondsInDay = (exports.millisecondsInDay = 86400000);\n\n/**\n * @constant\n * @name millisecondsInMinute\n * @summary Milliseconds in 1 minute\n */\nconst millisecondsInMinute = (exports.millisecondsInMinute = 60000);\n\n/**\n * @constant\n * @name millisecondsInHour\n * @summary Milliseconds in 1 hour\n */\nconst millisecondsInHour = (exports.millisecondsInHour = 3600000);\n\n/**\n * @constant\n * @name millisecondsInSecond\n * @summary Milliseconds in 1 second\n */\nconst millisecondsInSecond = (exports.millisecondsInSecond = 1000);\n\n/**\n * @constant\n * @name minutesInYear\n * @summary Minutes in 1 year.\n */\nconst minutesInYear = (exports.minutesInYear = 525600);\n\n/**\n * @constant\n * @name minutesInMonth\n * @summary Minutes in 1 month.\n */\nconst minutesInMonth = (exports.minutesInMonth = 43200);\n\n/**\n * @constant\n * @name minutesInDay\n * @summary Minutes in 1 day.\n */\nconst minutesInDay = (exports.minutesInDay = 1440);\n\n/**\n * @constant\n * @name minutesInHour\n * @summary Minutes in 1 hour.\n */\nconst minutesInHour = (exports.minutesInHour = 60);\n\n/**\n * @constant\n * @name monthsInQuarter\n * @summary Months in 1 quarter.\n */\nconst monthsInQuarter = (exports.monthsInQuarter = 3);\n\n/**\n * @constant\n * @name monthsInYear\n * @summary Months in 1 year.\n */\nconst monthsInYear = (exports.monthsInYear = 12);\n\n/**\n * @constant\n * @name quartersInYear\n * @summary Quarters in 1 year\n */\nconst quartersInYear = (exports.quartersInYear = 4);\n\n/**\n * @constant\n * @name secondsInHour\n * @summary Seconds in 1 hour.\n */\nconst secondsInHour = (exports.secondsInHour = 3600);\n\n/**\n * @constant\n * @name secondsInMinute\n * @summary Seconds in 1 minute.\n */\nconst secondsInMinute = (exports.secondsInMinute = 60);\n\n/**\n * @constant\n * @name secondsInDay\n * @summary Seconds in 1 day.\n */\nconst secondsInDay = (exports.secondsInDay = secondsInHour * 24);\n\n/**\n * @constant\n * @name secondsInWeek\n * @summary Seconds in 1 week.\n */\nconst secondsInWeek = (exports.secondsInWeek = secondsInDay * 7);\n\n/**\n * @constant\n * @name secondsInYear\n * @summary Seconds in 1 year.\n */\nconst secondsInYear = (exports.secondsInYear = secondsInDay * daysInYear);\n\n/**\n * @constant\n * @name secondsInMonth\n * @summary Seconds in 1 month\n */\nconst secondsInMonth = (exports.secondsInMonth = secondsInYear / 12);\n\n/**\n * @constant\n * @name secondsInQuarter\n * @summary Seconds in 1 quarter.\n */\nconst secondsInQuarter = (exports.secondsInQuarter = secondsInMonth * 3);\n\n/**\n * @constant\n * @name constructFromSymbol\n * @summary Symbol enabling Date extensions to inherit properties from the reference date.\n *\n * The symbol is used to enable the `constructFrom` function to construct a date\n * using a reference date and a value. It allows to transfer extra properties\n * from the reference date to the new date. It's useful for extensions like\n * [`TZDate`](https://github.com/date-fns/tz) that accept a time zone as\n * a constructor argument.\n */\nconst constructFromSymbol = (exports.constructFromSymbol =\n Symbol.for(\"constructDateFrom\"));\n", "\"use strict\";\nexports.constructFrom = constructFrom;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name constructFrom\n * @category Generic Helpers\n * @summary Constructs a date using the reference date and the value\n *\n * @description\n * The function constructs a new date using the constructor from the reference\n * date and the given value. It helps to build generic functions that accept\n * date extensions.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * Starting from v3.7.0, it allows to construct a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The reference date to take constructor from\n * @param value - The value to create the date\n *\n * @returns Date initialized using the given date and value\n *\n * @example\n * import { constructFrom } from \"date-fns\";\n *\n * // A function that clones a date preserving the original type\n * function cloneDate(date: DateType): DateType {\n * return constructFrom(\n * date, // Use constructor from the given date\n * date.getTime() // Use the date value to create a new date\n * );\n * }\n */\nfunction constructFrom(date, value) {\n if (typeof date === \"function\") return date(value);\n\n if (date && typeof date === \"object\" && _index.constructFromSymbol in date)\n return date[_index.constructFromSymbol](value);\n\n if (date instanceof Date) return new date.constructor(value);\n\n return new Date(value);\n}\n", "\"use strict\";\nexports.toDate = toDate;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * Starting from v3.7.0, it clones a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Clone the date:\n * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert the timestamp to date:\n * const result = toDate(1392098430000)\n * //=> Tue Feb 11 2014 11:30:30\n */\nfunction toDate(argument, context) {\n // [TODO] Get rid of `toDate` or `constructFrom`?\n return (0, _index.constructFrom)(context || argument, argument);\n}\n", "\"use strict\";\nexports.addDays = addDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addDays} function options.\n */\n\n/**\n * @name addDays\n * @category Day Helpers\n * @summary Add the specified number of days to the given date.\n *\n * @description\n * Add the specified number of days to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the days added\n *\n * @example\n * // Add 10 days to 1 September 2014:\n * const result = addDays(new Date(2014, 8, 1), 10)\n * //=> Thu Sep 11 2014 00:00:00\n */\nfunction addDays(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n // If 0 days, no-op to avoid changing times in the hour before end of DST\n if (!amount) return _date;\n\n _date.setDate(_date.getDate() + amount);\n return _date;\n}\n", "\"use strict\";\nexports.addMonths = addMonths;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMonths} function options.\n */\n\n/**\n * @name addMonths\n * @category Month Helpers\n * @summary Add the specified number of months to the given date.\n *\n * @description\n * Add the specified number of months to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be added.\n * @param options - The options object\n *\n * @returns The new date with the months added\n *\n * @example\n * // Add 5 months to 1 September 2014:\n * const result = addMonths(new Date(2014, 8, 1), 5)\n * //=> Sun Feb 01 2015 00:00:00\n *\n * // Add one month to 30 January 2023:\n * const result = addMonths(new Date(2023, 0, 30), 1)\n * //=> Tue Feb 28 2023 00:00:00\n */\nfunction addMonths(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n if (!amount) {\n // If 0 months, no-op to avoid changing times in the hour before end of DST\n return _date;\n }\n const dayOfMonth = _date.getDate();\n\n // The JS Date object supports date math by accepting out-of-bounds values for\n // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and\n // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we\n // want except that dates will wrap around the end of a month, meaning that\n // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So\n // we'll default to the end of the desired month by adding 1 to the desired\n // month and using a date of 0 to back up one day to the end of the desired\n // month.\n const endOfDesiredMonth = (0, _index.constructFrom)(\n options?.in || date,\n _date.getTime(),\n );\n endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);\n const daysInMonth = endOfDesiredMonth.getDate();\n if (dayOfMonth >= daysInMonth) {\n // If we're already at the end of the month, then this is the correct date\n // and we're done.\n return endOfDesiredMonth;\n } else {\n // Otherwise, we now know that setting the original day-of-month value won't\n // cause an overflow, so set the desired day-of-month. Note that we can't\n // just set the date of `endOfDesiredMonth` because that object may have had\n // its time changed in the unusual case where where a DST transition was on\n // the last day of the month and its local time was in the hour skipped or\n // repeated next to a DST transition. So we use `date` instead which is\n // guaranteed to still have the original time.\n _date.setFullYear(\n endOfDesiredMonth.getFullYear(),\n endOfDesiredMonth.getMonth(),\n dayOfMonth,\n );\n return _date;\n }\n}\n", "\"use strict\";\nexports.add = add;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./addMonths.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link add} function options.\n */\n\n/**\n * @name add\n * @category Common Helpers\n * @summary Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @description\n * Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @typeParam DateType - The `Date` type the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes, and seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add the following duration to 1 September 2014, 10:19:50\n * const result = add(new Date(2014, 8, 1, 10, 19, 50), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30,\n * })\n * //=> Thu Jun 15 2017 15:29:20\n */\nfunction add(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n // Add years and months\n const _date = (0, _index4.toDate)(date, options?.in);\n const dateWithMonths =\n months || years\n ? (0, _index2.addMonths)(_date, months + years * 12)\n : _date;\n\n // Add weeks and days\n const dateWithDays =\n days || weeks\n ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)\n : dateWithMonths;\n\n // Add days, hours, minutes, and seconds\n const minutesToAdd = minutes + hours * 60;\n const secondsToAdd = seconds + minutesToAdd * 60;\n const msToAdd = secondsToAdd * 1000;\n\n return (0, _index3.constructFrom)(\n options?.in || date,\n +dateWithDays + msToAdd,\n );\n}\n", "\"use strict\";\nexports.isSaturday = isSaturday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSaturday} function options.\n */\n\n/**\n * @name isSaturday\n * @category Weekday Helpers\n * @summary Is the given date Saturday?\n *\n * @description\n * Is the given date Saturday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Saturday\n *\n * @example\n * // Is 27 September 2014 Saturday?\n * const result = isSaturday(new Date(2014, 8, 27))\n * //=> true\n */\nfunction isSaturday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 6;\n}\n", "\"use strict\";\nexports.isSunday = isSunday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSunday} function options.\n */\n\n/**\n * @name isSunday\n * @category Weekday Helpers\n * @summary Is the given date Sunday?\n *\n * @description\n * Is the given date Sunday?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is Sunday\n *\n * @example\n * // Is 21 September 2014 Sunday?\n * const result = isSunday(new Date(2014, 8, 21))\n * //=> true\n */\nfunction isSunday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 0;\n}\n", "\"use strict\";\nexports.isWeekend = isWeekend;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWeekend} function options.\n */\n\n/**\n * @name isWeekend\n * @category Weekday Helpers\n * @summary Does the given date fall on a weekend?\n *\n * @description\n * Does the given date fall on a weekend? A weekend is either Saturday (`6`) or Sunday (`0`).\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date falls on a weekend\n *\n * @example\n * // Does 5 October 2014 fall on a weekend?\n * const result = isWeekend(new Date(2014, 9, 5))\n * //=> true\n */\nfunction isWeekend(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 || day === 6;\n}\n", "\"use strict\";\nexports.addBusinessDays = addBusinessDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./isSaturday.cjs\");\nvar _index3 = require(\"./isSunday.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addBusinessDays} function options.\n */\n\n/**\n * @name addBusinessDays\n * @category Day Helpers\n * @summary Add the specified number of business days (mon - fri) to the given date.\n *\n * @description\n * Add the specified number of business days (mon - fri) to the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the business days added\n *\n * @example\n * // Add 10 business days to 1 September 2014:\n * const result = addBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days)\n */\nfunction addBusinessDays(date, amount, options) {\n const _date = (0, _index5.toDate)(date, options?.in);\n const startedOnWeekend = (0, _index4.isWeekend)(_date, options);\n\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in, NaN);\n\n const hours = _date.getHours();\n const sign = amount < 0 ? -1 : 1;\n const fullWeeks = Math.trunc(amount / 5);\n\n _date.setDate(_date.getDate() + fullWeeks * 7);\n\n // Get remaining days not part of a full week\n let restDays = Math.abs(amount % 5);\n\n // Loops over remaining days\n while (restDays > 0) {\n _date.setDate(_date.getDate() + sign);\n if (!(0, _index4.isWeekend)(_date, options)) restDays -= 1;\n }\n\n // If the date is a weekend day and we reduce a dividable of\n // 5 from it, we land on a weekend date.\n // To counter this, we add days accordingly to land on the next business day\n if (\n startedOnWeekend &&\n (0, _index4.isWeekend)(_date, options) &&\n amount !== 0\n ) {\n // If we're reducing days, we want to add days until we land on a weekday\n // If we're adding days we want to reduce days until we land on a weekday\n if ((0, _index2.isSaturday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 2 : -1));\n if ((0, _index3.isSunday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 1 : -2));\n }\n\n // Restore hours to avoid DST lag\n _date.setHours(hours);\n\n return _date;\n}\n", "\"use strict\";\nexports.addMilliseconds = addMilliseconds;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMilliseconds} function options.\n */\n\n/**\n * @name addMilliseconds\n * @category Millisecond Helpers\n * @summary Add the specified number of milliseconds to the given date.\n *\n * @description\n * Add the specified number of milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be added.\n * @param options - The options object\n *\n * @returns The new date with the milliseconds added\n *\n * @example\n * // Add 750 milliseconds to 10 July 2014 12:45:30.000:\n * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)\n * //=> Thu Jul 10 2014 12:45:30.750\n */\nfunction addMilliseconds(date, amount, options) {\n return (0, _index.constructFrom)(\n options?.in || date,\n +(0, _index2.toDate)(date) + amount,\n );\n}\n", "\"use strict\";\nexports.addHours = addHours;\nvar _index = require(\"./addMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\n/**\n * The {@link addHours} function options.\n */\n\n/**\n * @name addHours\n * @category Hour Helpers\n * @summary Add the specified number of hours to the given date.\n *\n * @description\n * Add the specified number of hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be added\n * @param options - An object with options\n *\n * @returns The new date with the hours added\n *\n * @example\n * // Add 2 hours to 10 July 2014 23:00:00:\n * const result = addHours(new Date(2014, 6, 10, 23, 0), 2)\n * //=> Fri Jul 11 2014 01:00:00\n */\nfunction addHours(date, amount, options) {\n return (0, _index.addMilliseconds)(\n date,\n amount * _index2.millisecondsInHour,\n options,\n );\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\nexports.setDefaultOptions = setDefaultOptions;\n\nlet defaultOptions = {};\n\nfunction getDefaultOptions() {\n return defaultOptions;\n}\n\nfunction setDefaultOptions(newOptions) {\n defaultOptions = newOptions;\n}\n", "\"use strict\";\nexports.startOfWeek = startOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfWeek} function options.\n */\n\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n\n _date.setDate(_date.getDate() - diff);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfISOWeek = startOfISOWeek;\nvar _index = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfISOWeek} function options.\n */\n\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfISOWeek(date, options) {\n return (0, _index.startOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.getISOWeekYear = getISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeekYear} function options.\n */\n\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n *\n * @returns The ISO week-numbering year\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nfunction getISOWeekYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfNextYear,\n );\n\n const fourthOfJanuaryOfThisYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfThisYear,\n );\n\n if (_date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (_date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.getTimezoneOffsetInMilliseconds = getTimezoneOffsetInMilliseconds;\nvar _index = require(\"../toDate.cjs\");\n\n/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nfunction getTimezoneOffsetInMilliseconds(date) {\n const _date = (0, _index.toDate)(date);\n const utcDate = new Date(\n Date.UTC(\n _date.getFullYear(),\n _date.getMonth(),\n _date.getDate(),\n _date.getHours(),\n _date.getMinutes(),\n _date.getSeconds(),\n _date.getMilliseconds(),\n ),\n );\n utcDate.setUTCFullYear(_date.getFullYear());\n return +date - +utcDate;\n}\n", "\"use strict\";\nexports.normalizeDates = normalizeDates;\nvar _index = require(\"../constructFrom.cjs\");\n\nfunction normalizeDates(context, ...dates) {\n const normalize = _index.constructFrom.bind(\n null,\n context || dates.find((date) => typeof date === \"object\"),\n );\n return dates.map(normalize);\n}\n", "\"use strict\";\nexports.startOfDay = startOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDay} function options.\n */\n\n/**\n * @name startOfDay\n * @category Day Helpers\n * @summary Return the start of a day for the given date.\n *\n * @description\n * Return the start of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a day\n *\n * @example\n * // The start of a day for 2 September 2014 11:55:00:\n * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 00:00:00\n */\nfunction startOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.differenceInCalendarDays = differenceInCalendarDays;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link differenceInCalendarDays} function options.\n */\n\n/**\n * @name differenceInCalendarDays\n * @category Day Helpers\n * @summary Get the number of calendar days between the given dates.\n *\n * @description\n * Get the number of calendar days between the given dates. This means that the times are removed\n * from the dates and then the difference in days is calculated.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options object\n *\n * @returns The number of calendar days\n *\n * @example\n * // How many calendar days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInCalendarDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 366\n * // How many calendar days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInCalendarDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 1\n */\nfunction differenceInCalendarDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfDay = (0, _index4.startOfDay)(laterDate_);\n const earlierStartOfDay = (0, _index4.startOfDay)(earlierDate_);\n\n const laterTimestamp =\n +laterStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfDay);\n const earlierTimestamp =\n +earlierStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfDay);\n\n // Round the number of days to the nearest integer because the number of\n // milliseconds in a day is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInDay,\n );\n}\n", "\"use strict\";\nexports.startOfISOWeekYear = startOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link startOfISOWeekYear} function options.\n */\n\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week-numbering year\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n return (0, _index3.startOfISOWeek)(fourthOfJanuary);\n}\n", "\"use strict\";\nexports.setISOWeekYear = setISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeekYear} function options.\n */\n\n/**\n * @name setISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Set the ISO week-numbering year to the given date.\n *\n * @description\n * Set the ISO week-numbering year to the given date,\n * saving the week number and the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The ISO week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering year set\n *\n * @example\n * // Set ISO week-numbering year 2007 to 29 December 2008:\n * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)\n * //=> Mon Jan 01 2007 00:00:00\n */\nfunction setISOWeekYear(date, weekYear, options) {\n let _date = (0, _index4.toDate)(date, options?.in);\n const diff = (0, _index2.differenceInCalendarDays)(\n _date,\n (0, _index3.startOfISOWeekYear)(_date, options),\n );\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(weekYear, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n _date = (0, _index3.startOfISOWeekYear)(fourthOfJanuary);\n _date.setDate(_date.getDate() + diff);\n return _date;\n}\n", "\"use strict\";\nexports.addISOWeekYears = addISOWeekYears;\nvar _index = require(\"./getISOWeekYear.cjs\");\nvar _index2 = require(\"./setISOWeekYear.cjs\");\n\n/**\n * The {@link addISOWeekYears} function options.\n */\n\n/**\n * @name addISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Add the specified number of ISO week-numbering years to the given date.\n *\n * @description\n * Add the specified number of ISO week-numbering years to the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be added.\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering years added\n *\n * @example\n * // Add 5 ISO week-numbering years to 2 July 2010:\n * const result = addISOWeekYears(new Date(2010, 6, 2), 5)\n * //=> Fri Jun 26 2015 00:00:00\n */\nfunction addISOWeekYears(date, amount, options) {\n return (0, _index2.setISOWeekYear)(\n date,\n (0, _index.getISOWeekYear)(date, options) + amount,\n options,\n );\n}\n", "\"use strict\";\nexports.addMinutes = addMinutes;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMinutes} function options.\n */\n\n/**\n * @name addMinutes\n * @category Minute Helpers\n * @summary Add the specified number of minutes to the given date.\n *\n * @description\n * Add the specified number of minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be added.\n * @param options - An object with options\n *\n * @returns The new date with the minutes added\n *\n * @example\n * // Add 30 minutes to 10 July 2014 12:00:00:\n * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction addMinutes(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n _date.setTime(_date.getTime() + amount * _index.millisecondsInMinute);\n return _date;\n}\n", "\"use strict\";\nexports.addQuarters = addQuarters;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addQuarters} function options.\n */\n\n/**\n * @name addQuarters\n * @category Quarter Helpers\n * @summary Add the specified number of year quarters to the given date.\n *\n * @description\n * Add the specified number of year quarters to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be added.\n * @param options - An object with options\n *\n * @returns The new date with the quarters added\n *\n * @example\n * // Add 1 quarter to 1 September 2014:\n * const result = addQuarters(new Date(2014, 8, 1), 1)\n * //=; Mon Dec 01 2014 00:00:00\n */\nfunction addQuarters(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 3, options);\n}\n", "\"use strict\";\nexports.addSeconds = addSeconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link addSeconds} function options.\n */\n\n/**\n * @name addSeconds\n * @category Second Helpers\n * @summary Add the specified number of seconds to the given date.\n *\n * @description\n * Add the specified number of seconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add 30 seconds to 10 July 2014 12:45:00:\n * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:45:30\n */\nfunction addSeconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, amount * 1000, options);\n}\n", "\"use strict\";\nexports.addWeeks = addWeeks;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link addWeeks} function options.\n */\n\n/**\n * @name addWeeks\n * @category Week Helpers\n * @summary Add the specified number of weeks to the given date.\n *\n * @description\n * Add the specified number of weeks to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be added.\n * @param options - An object with options\n *\n * @returns The new date with the weeks added\n *\n * @example\n * // Add 4 weeks to 1 September 2014:\n * const result = addWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Sep 29 2014 00:00:00\n */\nfunction addWeeks(date, amount, options) {\n return (0, _index.addDays)(date, amount * 7, options);\n}\n", "\"use strict\";\nexports.addYears = addYears;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addYears} function options.\n */\n\n/**\n * @name addYears\n * @category Year Helpers\n * @summary Add the specified number of years to the given date.\n *\n * @description\n * Add the specified number of years to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be added.\n * @param options - The options\n *\n * @returns The new date with the years added\n *\n * @example\n * // Add 5 years to 1 September 2014:\n * const result = addYears(new Date(2014, 8, 1), 5)\n * //=> Sun Sep 01 2019 00:00:00\n */\nfunction addYears(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 12, options);\n}\n", "\"use strict\";\nexports.areIntervalsOverlapping = areIntervalsOverlapping;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link areIntervalsOverlapping} function options.\n */\n\n/**\n * @name areIntervalsOverlapping\n * @category Interval Helpers\n * @summary Is the given time interval overlapping with another time interval?\n *\n * @description\n * Is the given time interval overlapping with another time interval? Adjacent intervals do not count as overlapping unless `inclusive` is set to `true`.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - The object with options\n *\n * @returns Whether the time intervals are overlapping\n *\n * @example\n * // For overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> true\n *\n * @example\n * // For non-overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> false\n *\n * @example\n * // For adjacent time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 30) }\n * )\n * //=> false\n *\n * @example\n * // Using the inclusive option:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 24) },\n * { inclusive: true }\n * )\n * //=> true\n */\nfunction areIntervalsOverlapping(intervalLeft, intervalRight, options) {\n const [leftStartTime, leftEndTime] = [\n +(0, _index.toDate)(intervalLeft.start, options?.in),\n +(0, _index.toDate)(intervalLeft.end, options?.in),\n ].sort((a, b) => a - b);\n const [rightStartTime, rightEndTime] = [\n +(0, _index.toDate)(intervalRight.start, options?.in),\n +(0, _index.toDate)(intervalRight.end, options?.in),\n ].sort((a, b) => a - b);\n\n if (options?.inclusive)\n return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;\n\n return leftStartTime < rightEndTime && rightStartTime < leftEndTime;\n}\n", "\"use strict\";\nexports.max = max;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link max} function options.\n */\n\n/**\n * @name max\n * @category Common Helpers\n * @summary Return the latest of the given dates.\n *\n * @description\n * Return the latest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The latest of the dates\n *\n * @example\n * // Which of these dates is the latest?\n * const result = max([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Sun Jul 02 1995 00:00:00\n */\nfunction max(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result < date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.min = min;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link min} function options.\n */\n\n/**\n * @name min\n * @category Common Helpers\n * @summary Returns the earliest of the given dates.\n *\n * @description\n * Returns the earliest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The earliest of the dates\n *\n * @example\n * // Which of these dates is the earliest?\n * const result = min([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Wed Feb 11 1987 00:00:00\n */\nfunction min(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result > date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.clamp = clamp;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./max.cjs\");\nvar _index3 = require(\"./min.cjs\");\n\n/**\n * The {@link clamp} function options.\n */\n\n/**\n * The {@link clamp} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name clamp\n * @category Interval Helpers\n * @summary Return a date bounded by the start and the end of the given interval.\n *\n * @description\n * Clamps a date to the lower bound with the start of the interval and the upper\n * bound with the end of the interval.\n *\n * - When the date is less than the start of the interval, the start is returned.\n * - When the date is greater than the end of the interval, the end is returned.\n * - Otherwise the date is returned.\n *\n * @typeParam DateType - Date argument type.\n * @typeParam IntervalType - Interval argument type.\n * @typeParam Options - Options type.\n *\n * @param date - The date to be bounded\n * @param interval - The interval to bound to\n * @param options - An object with options\n *\n * @returns The date bounded by the start and the end of the interval\n *\n * @example\n * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021\n * const result = clamp(new Date(2021, 2, 21), {\n * start: new Date(2021, 2, 22),\n * end: new Date(2021, 3, 1),\n * })\n * //=> Mon Mar 22 2021 00:00:00\n */\nfunction clamp(date, interval, options) {\n const [date_, start, end] = (0, _index.normalizeDates)(\n options?.in,\n date,\n interval.start,\n interval.end,\n );\n\n return (0, _index3.min)(\n [(0, _index2.max)([date_, start], options), end],\n options,\n );\n}\n", "\"use strict\";\nexports.closestIndexTo = closestIndexTo;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name closestIndexTo\n * @category Common Helpers\n * @summary Return an index of the closest date from the array comparing to the given date.\n *\n * @description\n * Return an index of the closest date from the array comparing to the given date.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns An index of the date closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015?\n * const dateToCompare = new Date(2015, 8, 6)\n * const datesArray = [\n * new Date(2015, 0, 1),\n * new Date(2016, 0, 1),\n * new Date(2017, 0, 1)\n * ]\n * const result = closestIndexTo(dateToCompare, datesArray)\n * //=> 1\n */\nfunction closestIndexTo(dateToCompare, dates) {\n // [TODO] It would be better to return -1 here rather than undefined, as this\n // is how JS behaves, but it would be a breaking change, so we need\n // to consider it for v4.\n const timeToCompare = +(0, _index.toDate)(dateToCompare);\n\n if (isNaN(timeToCompare)) return NaN;\n\n let result;\n let minDistance;\n dates.forEach((date, index) => {\n const date_ = (0, _index.toDate)(date);\n\n if (isNaN(+date_)) {\n result = NaN;\n minDistance = NaN;\n return;\n }\n\n const distance = Math.abs(timeToCompare - +date_);\n if (result == null || distance < minDistance) {\n result = index;\n minDistance = distance;\n }\n });\n\n return result;\n}\n", "\"use strict\";\nexports.closestTo = closestTo;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./closestIndexTo.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link closestTo} function options.\n */\n\n/**\n * The {@link closestTo} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name closestTo\n * @category Common Helpers\n * @summary Return a date from the array closest to the given date.\n *\n * @description\n * Return a date from the array closest to the given date.\n *\n * @typeParam DateToCompare - Date to compare argument type.\n * @typeParam DatesType - Dates array argument type.\n * @typeParam Options - Options type.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns The date from the array closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?\n * const dateToCompare = new Date(2015, 8, 6)\n * const result = closestTo(dateToCompare, [\n * new Date(2000, 0, 1),\n * new Date(2030, 0, 1)\n * ])\n * //=> Tue Jan 01 2030 00:00:00\n */\nfunction closestTo(dateToCompare, dates, options) {\n const [dateToCompare_, ...dates_] = (0, _index.normalizeDates)(\n options?.in,\n dateToCompare,\n ...dates,\n );\n\n const index = (0, _index2.closestIndexTo)(dateToCompare_, dates_);\n\n if (typeof index === \"number\" && isNaN(index))\n return (0, _index3.constructFrom)(dateToCompare_, NaN);\n\n if (index !== undefined) return dates_[index];\n}\n", "\"use strict\";\nexports.compareAsc = compareAsc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareAsc\n * @category Common Helpers\n * @summary Compare the two dates and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return 1 if the first date is after the second,\n * -1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989:\n * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> -1\n *\n * @example\n * // Sort the array of dates:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareAsc)\n * //=> [\n * // Wed Feb 11 1987 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Sun Jul 02 1995 00:00:00\n * // ]\n */\nfunction compareAsc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff < 0) return -1;\n else if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.compareDesc = compareDesc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareDesc\n * @category Common Helpers\n * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return -1 if the first date is after the second,\n * 1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:\n * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> 1\n *\n * @example\n * // Sort the array of dates in reverse chronological order:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareDesc)\n * //=> [\n * // Sun Jul 02 1995 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Wed Feb 11 1987 00:00:00\n * // ]\n */\nfunction compareDesc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff > 0) return -1;\n else if (diff < 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.constructNow = constructNow;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name constructNow\n * @category Generic Helpers\n * @summary Constructs a new current date using the passed value constructor.\n * @pure false\n *\n * @description\n * The function constructs a new current date using the constructor from\n * the reference date. It helps to build generic functions that accept date\n * extensions and use the current date.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * @param date - The reference date to take constructor from\n *\n * @returns Current date initialized using the given date constructor\n *\n * @example\n * import { constructNow, isSameDay } from 'date-fns'\n *\n * function isToday(\n * date: DateArg,\n * ): boolean {\n * // If we were to use `new Date()` directly, the function would behave\n * // differently in different timezones and return false for the same date.\n * return isSameDay(date, constructNow(date));\n * }\n */\nfunction constructNow(date) {\n return (0, _index.constructFrom)(date, Date.now());\n}\n", "\"use strict\";\nexports.daysToWeeks = daysToWeeks;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name daysToWeeks\n * @category Conversion Helpers\n * @summary Convert days to weeks.\n *\n * @description\n * Convert a number of days to a full number of weeks.\n *\n * @param days - The number of days to be converted\n *\n * @returns The number of days converted in weeks\n *\n * @example\n * // Convert 14 days to weeks:\n * const result = daysToWeeks(14)\n * //=> 2\n *\n * @example\n * // It uses trunc rounding:\n * const result = daysToWeeks(13)\n * //=> 1\n */\nfunction daysToWeeks(days) {\n const result = Math.trunc(days / _index.daysInWeek);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.isSameDay = isSameDay;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link isSameDay} function options.\n */\n\n/**\n * @name isSameDay\n * @category Day Helpers\n * @summary Are the given dates in the same day (and year and month)?\n *\n * @description\n * Are the given dates in the same day (and year and month)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same day (and year and month)\n *\n * @example\n * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))\n * //=> true\n *\n * @example\n * // Are 4 September and 4 October in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))\n * //=> false\n *\n * @example\n * // Are 4 September, 2014 and 4 September, 2015 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))\n * //=> false\n */\nfunction isSameDay(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfDay)(dateLeft_) === +(0, _index2.startOfDay)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isDate = isDate; /**\n * @name isDate\n * @category Common Helpers\n * @summary Is the given value a date?\n *\n * @description\n * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.\n *\n * @param value - The value to check\n *\n * @returns True if the given value is a date\n *\n * @example\n * // For a valid date:\n * const result = isDate(new Date())\n * //=> true\n *\n * @example\n * // For an invalid date:\n * const result = isDate(new Date(NaN))\n * //=> true\n *\n * @example\n * // For some value:\n * const result = isDate('2014-02-31')\n * //=> false\n *\n * @example\n * // For an object:\n * const result = isDate({})\n * //=> false\n */\nfunction isDate(value) {\n return (\n value instanceof Date ||\n (typeof value === \"object\" &&\n Object.prototype.toString.call(value) === \"[object Date]\")\n );\n}\n", "\"use strict\";\nexports.isValid = isValid;\nvar _index = require(\"./isDate.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * @name isValid\n * @category Common Helpers\n * @summary Is the given date valid?\n *\n * @description\n * Returns false if argument is Invalid Date and true otherwise.\n * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)\n * Invalid Date is a Date, whose time value is NaN.\n *\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @param date - The date to check\n *\n * @returns The date is valid\n *\n * @example\n * // For the valid date:\n * const result = isValid(new Date(2014, 1, 31))\n * //=> true\n *\n * @example\n * // For the value, convertible into a date:\n * const result = isValid(1393804800000)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isValid(new Date(''))\n * //=> false\n */\nfunction isValid(date) {\n return !(\n (!(0, _index.isDate)(date) && typeof date !== \"number\") ||\n isNaN(+(0, _index2.toDate)(date))\n );\n}\n", "\"use strict\";\nexports.differenceInBusinessDays = differenceInBusinessDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./isSameDay.cjs\");\nvar _index5 = require(\"./isValid.cjs\");\nvar _index6 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link differenceInBusinessDays} function options.\n */\n\n/**\n * @name differenceInBusinessDays\n * @category Day Helpers\n * @summary Get the number of business days between the given dates.\n *\n * @description\n * Get the number of business day periods between the given dates.\n * Business days being days that aren't in the weekend.\n * Like `differenceInCalendarDays`, the function removes the times from\n * the dates before calculating the difference.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of business days\n *\n * @example\n * // How many business days are between\n * // 10 January 2014 and 20 July 2014?\n * const result = differenceInBusinessDays(\n * new Date(2014, 6, 20),\n * new Date(2014, 0, 10)\n * )\n * //=> 136\n *\n * // How many business days are between\n * // 30 November 2021 and 1 November 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 30),\n * new Date(2021, 10, 1)\n * )\n * //=> 21\n *\n * // How many business days are between\n * // 1 November 2021 and 1 December 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 11, 1)\n * )\n * //=> -22\n *\n * // How many business days are between\n * // 1 November 2021 and 1 November 2021 ?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 10, 1)\n * )\n * //=> 0\n */\nfunction differenceInBusinessDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!(0, _index5.isValid)(laterDate_) || !(0, _index5.isValid)(earlierDate_))\n return NaN;\n\n const diff = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n const sign = diff < 0 ? -1 : 1;\n const weeks = Math.trunc(diff / 7);\n\n let result = weeks * 5;\n let movingDate = (0, _index2.addDays)(earlierDate_, weeks * 7);\n\n // the loop below will run at most 6 times to account for the remaining days that don't makeup a full week\n while (!(0, _index4.isSameDay)(laterDate_, movingDate)) {\n // sign is used to account for both negative and positive differences\n result += (0, _index6.isWeekend)(movingDate, options) ? 0 : sign;\n movingDate = (0, _index2.addDays)(movingDate, sign);\n }\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeekYears = differenceInCalendarISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeekYears} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of calendar ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of calendar ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO week-numbering years\n *\n * @example\n * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012?\n * const result = differenceInCalendarISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * //=> 2\n */\nfunction differenceInCalendarISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n (0, _index2.getISOWeekYear)(laterDate_, options) -\n (0, _index2.getISOWeekYear)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeeks = differenceInCalendarISOWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeeks\n * @category ISO Week Helpers\n * @summary Get the number of calendar ISO weeks between the given dates.\n *\n * @description\n * Get the number of calendar ISO weeks between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO weeks\n *\n * @example\n * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?\n * const result = differenceInCalendarISOWeeks(\n * new Date(2014, 6, 21),\n * new Date(2014, 6, 6),\n * );\n * //=> 3\n */\nfunction differenceInCalendarISOWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const startOfISOWeekLeft = (0, _index4.startOfISOWeek)(laterDate_);\n const startOfISOWeekRight = (0, _index4.startOfISOWeek)(earlierDate_);\n\n const timestampLeft =\n +startOfISOWeekLeft -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekLeft);\n const timestampRight =\n +startOfISOWeekRight -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekRight);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (timestampLeft - timestampRight) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarMonths = differenceInCalendarMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarMonths} function options.\n */\n\n/**\n * @name differenceInCalendarMonths\n * @category Month Helpers\n * @summary Get the number of calendar months between the given dates.\n *\n * @description\n * Get the number of calendar months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar months\n *\n * @example\n * // How many calendar months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInCalendarMonths(\n * new Date(2014, 8, 1),\n * new Date(2014, 0, 31)\n * )\n * //=> 8\n */\nfunction differenceInCalendarMonths(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const monthsDiff = laterDate_.getMonth() - earlierDate_.getMonth();\n\n return yearsDiff * 12 + monthsDiff;\n}\n", "\"use strict\";\nexports.getQuarter = getQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getQuarter} function options.\n */\n\n/**\n * @name getQuarter\n * @category Quarter Helpers\n * @summary Get the year quarter of the given date.\n *\n * @description\n * Get the year quarter of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The quarter\n *\n * @example\n * // Which quarter is 2 July 2014?\n * const result = getQuarter(new Date(2014, 6, 2));\n * //=> 3\n */\nfunction getQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const quarter = Math.trunc(_date.getMonth() / 3) + 1;\n return quarter;\n}\n", "\"use strict\";\nexports.differenceInCalendarQuarters = differenceInCalendarQuarters;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getQuarter.cjs\");\n\n/**\n * The {@link differenceInCalendarQuarters} function options.\n */\n\n/**\n * @name differenceInCalendarQuarters\n * @category Quarter Helpers\n * @summary Get the number of calendar quarters between the given dates.\n *\n * @description\n * Get the number of calendar quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar quarters\n *\n * @example\n * // How many calendar quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInCalendarQuarters(\n * new Date(2014, 6, 2),\n * new Date(2013, 11, 31)\n * )\n * //=> 3\n */\nfunction differenceInCalendarQuarters(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const quartersDiff =\n (0, _index2.getQuarter)(laterDate_) - (0, _index2.getQuarter)(earlierDate_);\n\n return yearsDiff * 4 + quartersDiff;\n}\n", "\"use strict\";\nexports.differenceInCalendarWeeks = differenceInCalendarWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarWeeks\n * @category Week Helpers\n * @summary Get the number of calendar weeks between the given dates.\n *\n * @description\n * Get the number of calendar weeks between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5)\n * )\n * //=> 3\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5),\n * { weekStartsOn: 1 }\n * )\n * //=> 2\n */\nfunction differenceInCalendarWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfWeek = (0, _index4.startOfWeek)(laterDate_, options);\n const earlierStartOfWeek = (0, _index4.startOfWeek)(earlierDate_, options);\n\n const laterTimestamp =\n +laterStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfWeek);\n const earlierTimestamp =\n +earlierStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfWeek);\n\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarYears = differenceInCalendarYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarYears} function options.\n */\n\n/**\n * @name differenceInCalendarYears\n * @category Year Helpers\n * @summary Get the number of calendar years between the given dates.\n *\n * @description\n * Get the number of calendar years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n\n * @returns The number of calendar years\n *\n * @example\n * // How many calendar years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInCalendarYears(\n * new Date(2015, 1, 11),\n * new Date(2013, 11, 31)\n * );\n * //=> 2\n */\nfunction differenceInCalendarYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() - earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.differenceInDays = differenceInDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\n\n/**\n * The {@link differenceInDays} function options.\n */\n\n/**\n * @name differenceInDays\n * @category Day Helpers\n * @summary Get the number of full days between the given dates.\n *\n * @description\n * Get the number of full day periods between two dates. Fractional days are\n * truncated towards zero.\n *\n * One \"full day\" is the distance between a local time in one day to the same\n * local time on the next or previous day. A full day can sometimes be less than\n * or more than 24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/24)|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full days according to the local timezone\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 365\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 0\n *\n * @example\n * // How many full days are between\n * // 1 March 2020 0:00 and 1 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 92 days, even in\n * // time zones where DST starts and the\n * // period has only 92*24-1 hours.\n * const result = differenceInDays(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 1)\n * )\n * //=> 92\n */\nfunction differenceInDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = compareLocalAsc(laterDate_, earlierDate_);\n const difference = Math.abs(\n (0, _index2.differenceInCalendarDays)(laterDate_, earlierDate_),\n );\n\n laterDate_.setDate(laterDate_.getDate() - sign * difference);\n\n // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full\n // If so, result must be decreased by 1 in absolute value\n const isLastDayNotFull = Number(\n compareLocalAsc(laterDate_, earlierDate_) === -sign,\n );\n\n const result = sign * (difference - isLastDayNotFull);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n\n// Like `compareAsc` but uses local time not UTC, which is needed\n// for accurate equality comparisons of UTC timestamps that end up\n// having the same representation in local time, e.g. one hour before\n// DST ends vs. the instant that DST ends.\nfunction compareLocalAsc(laterDate, earlierDate) {\n const diff =\n laterDate.getFullYear() - earlierDate.getFullYear() ||\n laterDate.getMonth() - earlierDate.getMonth() ||\n laterDate.getDate() - earlierDate.getDate() ||\n laterDate.getHours() - earlierDate.getHours() ||\n laterDate.getMinutes() - earlierDate.getMinutes() ||\n laterDate.getSeconds() - earlierDate.getSeconds() ||\n laterDate.getMilliseconds() - earlierDate.getMilliseconds();\n\n if (diff < 0) return -1;\n if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.getRoundingMethod = getRoundingMethod;\n\nfunction getRoundingMethod(method) {\n return (number) => {\n const round = method ? Math[method] : Math.trunc;\n const result = round(number);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n };\n}\n", "\"use strict\";\nexports.differenceInHours = differenceInHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\n\n/**\n * The {@link differenceInHours} function options.\n */\n\n/**\n * @name differenceInHours\n * @category Hour Helpers\n * @summary Get the number of hours between the given dates.\n *\n * @description\n * Get the number of hours between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of hours\n *\n * @example\n * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?\n * const result = differenceInHours(\n * new Date(2014, 6, 2, 19, 0),\n * new Date(2014, 6, 2, 6, 50)\n * )\n * //=> 12\n */\nfunction differenceInHours(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n const diff = (+laterDate_ - +earlierDate_) / _index3.millisecondsInHour;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.subISOWeekYears = subISOWeekYears;\nvar _index = require(\"./addISOWeekYears.cjs\");\n\n/**\n * The {@link subISOWeekYears} function options.\n */\n\n/**\n * @name subISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Subtract the specified number of ISO week-numbering years from the given date.\n *\n * @description\n * Subtract the specified number of ISO week-numbering years from the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the ISO week-numbering years subtracted\n *\n * @example\n * // Subtract 5 ISO week-numbering years from 1 September 2014:\n * const result = subISOWeekYears(new Date(2014, 8, 1), 5)\n * //=> Mon Aug 31 2009 00:00:00\n */\nfunction subISOWeekYears(date, amount, options) {\n return (0, _index.addISOWeekYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.differenceInISOWeekYears = differenceInISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nvar _index4 = require(\"./subISOWeekYears.cjs\");\n\n/**\n * The {@link differenceInISOWeekYears} function options.\n */\n\n/**\n * @name differenceInISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of full ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of full ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options\n *\n * @returns The number of full ISO week-numbering years\n *\n * @example\n * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?\n * const result = differenceInISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * // => 1\n */\nfunction differenceInISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n const diff = Math.abs(\n (0, _index3.differenceInCalendarISOWeekYears)(\n laterDate_,\n earlierDate_,\n options,\n ),\n );\n\n const adjustedDate = (0, _index4.subISOWeekYears)(\n laterDate_,\n sign * diff,\n options,\n );\n\n const isLastISOWeekYearNotFull = Number(\n (0, _index2.compareAsc)(adjustedDate, earlierDate_) === -sign,\n );\n const result = sign * (diff - isLastISOWeekYearNotFull);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInMilliseconds = differenceInMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name differenceInMilliseconds\n * @category Millisecond Helpers\n * @summary Get the number of milliseconds between the given dates.\n *\n * @description\n * Get the number of milliseconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n *\n * @returns The number of milliseconds\n *\n * @example\n * // How many milliseconds are between\n * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?\n * const result = differenceInMilliseconds(\n * new Date(2014, 6, 2, 12, 30, 21, 700),\n * new Date(2014, 6, 2, 12, 30, 20, 600)\n * )\n * //=> 1100\n */\nfunction differenceInMilliseconds(laterDate, earlierDate) {\n return +(0, _index.toDate)(laterDate) - +(0, _index.toDate)(earlierDate);\n}\n", "\"use strict\";\nexports.differenceInMinutes = differenceInMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInMinutes} function options.\n */\n\n/**\n * @name differenceInMinutes\n * @category Minute Helpers\n * @summary Get the number of minutes between the given dates.\n *\n * @description\n * Get the signed number of full (rounded towards 0) minutes between the given dates.\n *\n * @param dateLeft - The later date\n * @param dateRight - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of minutes\n *\n * @example\n * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?\n * const result = differenceInMinutes(\n * new Date(2014, 6, 2, 12, 20, 0),\n * new Date(2014, 6, 2, 12, 7, 59)\n * )\n * //=> 12\n *\n * @example\n * // How many minutes are between 10:01:59 and 10:00:00\n * const result = differenceInMinutes(\n * new Date(2000, 0, 1, 10, 0, 0),\n * new Date(2000, 0, 1, 10, 1, 59)\n * )\n * //=> -1\n */\nfunction differenceInMinutes(dateLeft, dateRight, options) {\n const diff =\n (0, _index3.differenceInMilliseconds)(dateLeft, dateRight) /\n _index2.millisecondsInMinute;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.endOfDay = endOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDay} function options.\n */\n\n/**\n * @name endOfDay\n * @category Day Helpers\n * @summary Return the end of a day for the given date.\n *\n * @description\n * Return the end of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a day\n *\n * @example\n * // The end of a day for 2 September 2014 11:55:00:\n * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 23:59:59.999\n */\nfunction endOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMonth = endOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMonth} function options.\n */\n\n/**\n * @name endOfMonth\n * @category Month Helpers\n * @summary Return the end of a month for the given date.\n *\n * @description\n * Return the end of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a month\n *\n * @example\n * // The end of a month for 2 September 2014 11:55:00:\n * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.isLastDayOfMonth = isLastDayOfMonth;\nvar _index = require(\"./endOfDay.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name isLastDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the last day of a month?\n *\n * @description\n * Is the given date the last day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the last day of a month\n *\n * @example\n * // Is 28 February 2014 the last day of a month?\n * const result = isLastDayOfMonth(new Date(2014, 1, 28))\n * //=> true\n */\nfunction isLastDayOfMonth(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n return (\n +(0, _index.endOfDay)(_date, options) ===\n +(0, _index2.endOfMonth)(_date, options)\n );\n}\n", "\"use strict\";\nexports.differenceInMonths = differenceInMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index4 = require(\"./isLastDayOfMonth.cjs\");\n\n/**\n * The {@link differenceInMonths} function options.\n */\n\n/**\n * @name differenceInMonths\n * @category Month Helpers\n * @summary Get the number of full months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full months\n *\n * @example\n * // How many full months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))\n * //=> 7\n */\nfunction differenceInMonths(laterDate, earlierDate, options) {\n const [laterDate_, workingLaterDate, earlierDate_] = (0,\n _index.normalizeDates)(options?.in, laterDate, laterDate, earlierDate);\n\n const sign = (0, _index2.compareAsc)(workingLaterDate, earlierDate_);\n const difference = Math.abs(\n (0, _index3.differenceInCalendarMonths)(workingLaterDate, earlierDate_),\n );\n\n if (difference < 1) return 0;\n\n if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)\n workingLaterDate.setDate(30);\n\n workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);\n\n let isLastMonthNotFull =\n (0, _index2.compareAsc)(workingLaterDate, earlierDate_) === -sign;\n\n if (\n (0, _index4.isLastDayOfMonth)(laterDate_) &&\n difference === 1 &&\n (0, _index2.compareAsc)(laterDate_, earlierDate_) === 1\n ) {\n isLastMonthNotFull = false;\n }\n\n const result = sign * (difference - +isLastMonthNotFull);\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInQuarters = differenceInQuarters;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMonths.cjs\");\n\n/**\n * The {@link differenceInQuarters} function options.\n */\n\n/**\n * @name differenceInQuarters\n * @category Quarter Helpers\n * @summary Get the number of quarters between the given dates.\n *\n * @description\n * Get the number of quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of full quarters\n *\n * @example\n * // How many full quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))\n * //=> 2\n */\nfunction differenceInQuarters(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMonths)(laterDate, earlierDate, options) / 3;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInSeconds = differenceInSeconds;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInSeconds} function options.\n */\n\n/**\n * @name differenceInSeconds\n * @category Second Helpers\n * @summary Get the number of seconds between the given dates.\n *\n * @description\n * Get the number of seconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of seconds\n *\n * @example\n * // How many seconds are between\n * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?\n * const result = differenceInSeconds(\n * new Date(2014, 6, 2, 12, 30, 20, 0),\n * new Date(2014, 6, 2, 12, 30, 7, 999)\n * )\n * //=> 12\n */\nfunction differenceInSeconds(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMilliseconds)(laterDate, earlierDate) / 1000;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInWeeks = differenceInWeeks;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInDays.cjs\");\n\n/**\n * The {@link differenceInWeeks} function options.\n */\n\n/**\n * @name differenceInWeeks\n * @category Week Helpers\n * @summary Get the number of full weeks between the given dates.\n *\n * @description\n * Get the number of full weeks between two dates. Fractional weeks are\n * truncated towards zero by default.\n *\n * One \"full week\" is the distance between a local time in one day to the same\n * local time 7 days earlier or later. A full week can sometimes be less than\n * or more than 7*24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 7*24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/(7*24))|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full weeks\n *\n * @example\n * // How many full weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))\n * //=> 2\n *\n * @example\n * // How many full weeks are between\n * // 1 March 2020 0:00 and 6 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 8 weeks (54 days),\n * // even if DST starts and the period has\n * // only 54*24-1 hours.\n * const result = differenceInWeeks(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 6)\n * )\n * //=> 8\n */\nfunction differenceInWeeks(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInDays)(laterDate, earlierDate, options) / 7;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInYears = differenceInYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarYears.cjs\");\n\n/**\n * The {@link differenceInYears} function options.\n */\n\n/**\n * @name differenceInYears\n * @category Year Helpers\n * @summary Get the number of full years between the given dates.\n *\n * @description\n * Get the number of full years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full years\n *\n * @example\n * // How many full years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))\n * //=> 1\n */\nfunction differenceInYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n // -1 if the left date is earlier than the right date\n // 2023-12-31 - 2024-01-01 = -1\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n\n // First calculate the difference in calendar years\n // 2024-01-01 - 2023-12-31 = 1 year\n const diff = Math.abs(\n (0, _index3.differenceInCalendarYears)(laterDate_, earlierDate_),\n );\n\n // Now we need to calculate if the difference is full. To do that we set\n // both dates to the same year and check if the both date's month and day\n // form a full year.\n laterDate_.setFullYear(1584);\n earlierDate_.setFullYear(1584);\n\n // For it to be true, when the later date is indeed later than the earlier date\n // (2026-02-01 - 2023-12-10 = 3 years), the difference is full if\n // the normalized later date is also later than the normalized earlier date.\n // In our example, 1584-02-01 is earlier than 1584-12-10, so the difference\n // is partial, hence we need to subtract 1 from the difference 3 - 1 = 2.\n const partial = (0, _index2.compareAsc)(laterDate_, earlierDate_) === -sign;\n\n const result = sign * (diff - +partial);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.normalizeInterval = normalizeInterval;\nvar _index = require(\"./normalizeDates.cjs\");\n\nfunction normalizeInterval(context, interval) {\n const [start, end] = (0, _index.normalizeDates)(\n context,\n interval.start,\n interval.end,\n );\n return { start, end };\n}\n", "\"use strict\";\nexports.eachDayOfInterval = eachDayOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachDayOfInterval} function options.\n */\n\n/**\n * The {@link eachDayOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachDayOfInterval\n * @category Interval Helpers\n * @summary Return the array of dates within the specified time interval.\n *\n * @description\n * Return the array of dates within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of days from the day of the interval start to the day of the interval end\n *\n * @example\n * // Each day between 6 October 2014 and 10 October 2014:\n * const result = eachDayOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 9, 10)\n * })\n * //=> [\n * // Mon Oct 06 2014 00:00:00,\n * // Tue Oct 07 2014 00:00:00,\n * // Wed Oct 08 2014 00:00:00,\n * // Thu Oct 09 2014 00:00:00,\n * // Fri Oct 10 2014 00:00:00\n * // ]\n */\nfunction eachDayOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setDate(date.getDate() + step);\n date.setHours(0, 0, 0, 0);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachHourOfInterval = eachHourOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachHourOfInterval} function options.\n */\n\n/**\n * The {@link eachHourOfInterval} function result type.\n * Resolves to the appropriate date type based on inputs.\n */\n\n/**\n * @name eachHourOfInterval\n * @category Interval Helpers\n * @summary Return the array of hours within the specified time interval.\n *\n * @description\n * Return the array of hours within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end\n *\n * @example\n * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00\n * const result = eachHourOfInterval({\n * start: new Date(2014, 9, 6, 12),\n * end: new Date(2014, 9, 6, 15)\n * });\n * //=> [\n * // Mon Oct 06 2014 12:00:00,\n * // Mon Oct 06 2014 13:00:00,\n * // Mon Oct 06 2014 14:00:00,\n * // Mon Oct 06 2014 15:00:00\n * // ]\n */\nfunction eachHourOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setMinutes(0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setHours(date.getHours() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMinuteOfInterval = eachMinuteOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addMinutes.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMinuteOfInterval} function options.\n */\n\n/**\n * The {@link eachMinuteOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachMinuteOfInterval\n * @category Interval Helpers\n * @summary Return the array of minutes within the specified time interval.\n *\n * @description\n * Returns the array of minutes within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of minutes from the minute of the interval start to the minute of the interval end\n *\n * @example\n * // Each minute between 14 October 2020, 13:00 and 14 October 2020, 13:03\n * const result = eachMinuteOfInterval({\n * start: new Date(2014, 9, 14, 13),\n * end: new Date(2014, 9, 14, 13, 3)\n * })\n * //=> [\n * // Wed Oct 14 2014 13:00:00,\n * // Wed Oct 14 2014 13:01:00,\n * // Wed Oct 14 2014 13:02:00,\n * // Wed Oct 14 2014 13:03:00\n * // ]\n */\nfunction eachMinuteOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n // Set to the start of the minute\n start.setSeconds(0, 0);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n let date = reversed ? end : start;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addMinutes)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMonthOfInterval = eachMonthOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMonthOfInterval} function options.\n */\n\n/**\n * The {@link eachMonthOfInterval} function result type. It resolves the proper data type.\n */\n\n/**\n * @name eachMonthOfInterval\n * @category Interval Helpers\n * @summary Return the array of months within the specified time interval.\n *\n * @description\n * Return the array of months within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of months from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each month between 6 February 2014 and 10 August 2014:\n * const result = eachMonthOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10)\n * })\n * //=> [\n * // Sat Feb 01 2014 00:00:00,\n * // Sat Mar 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Thu May 01 2014 00:00:00,\n * // Sun Jun 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // Fri Aug 01 2014 00:00:00\n * // ]\n */\nfunction eachMonthOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setDate(1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setMonth(date.getMonth() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.startOfQuarter = startOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfQuarter} function options.\n */\n\n/**\n * @name startOfQuarter\n * @category Quarter Helpers\n * @summary Return the start of a year quarter for the given date.\n *\n * @description\n * Return the start of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a quarter\n *\n * @example\n * // The start of a quarter for 2 September 2014 11:55:00:\n * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Jul 01 2014 00:00:00\n */\nfunction startOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3);\n _date.setMonth(month, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachQuarterOfInterval = eachQuarterOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addQuarters.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link eachQuarterOfInterval} function options.\n */\n\n/**\n * The {@link eachQuarterOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachQuarterOfInterval\n * @category Interval Helpers\n * @summary Return the array of quarters within the specified time interval.\n *\n * @description\n * Return the array of quarters within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval\n * @param options - An object with options\n *\n * @returns The array with starts of quarters from the quarter of the interval start to the quarter of the interval end\n *\n * @example\n * // Each quarter within interval 6 February 2014 - 10 August 2014:\n * const result = eachQuarterOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10),\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // ]\n */\nfunction eachQuarterOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed\n ? +(0, _index4.startOfQuarter)(start)\n : +(0, _index4.startOfQuarter)(end);\n let date = reversed\n ? (0, _index4.startOfQuarter)(end)\n : (0, _index4.startOfQuarter)(start);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addQuarters)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekOfInterval = eachWeekOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addWeeks.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link eachWeekOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the interval start date,\n * then the end interval date. If a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachWeekOfInterval\n * @category Interval Helpers\n * @summary Return the array of weeks within the specified time interval.\n *\n * @description\n * Return the array of weeks within the specified time interval.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of weeks from the week of the interval start to the week of the interval end\n *\n * @example\n * // Each week within interval 6 October 2014 - 23 November 2014:\n * const result = eachWeekOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 10, 23)\n * })\n * //=> [\n * // Sun Oct 05 2014 00:00:00,\n * // Sun Oct 12 2014 00:00:00,\n * // Sun Oct 19 2014 00:00:00,\n * // Sun Oct 26 2014 00:00:00,\n * // Sun Nov 02 2014 00:00:00,\n * // Sun Nov 09 2014 00:00:00,\n * // Sun Nov 16 2014 00:00:00,\n * // Sun Nov 23 2014 00:00:00\n * // ]\n */\nfunction eachWeekOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const startDateWeek = reversed\n ? (0, _index4.startOfWeek)(end, options)\n : (0, _index4.startOfWeek)(start, options);\n const endDateWeek = reversed\n ? (0, _index4.startOfWeek)(start, options)\n : (0, _index4.startOfWeek)(end, options);\n\n startDateWeek.setHours(15);\n endDateWeek.setHours(15);\n\n const endTime = +endDateWeek.getTime();\n let currentDate = startDateWeek;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+currentDate <= endTime) {\n currentDate.setHours(0);\n dates.push((0, _index3.constructFrom)(start, currentDate));\n currentDate = (0, _index2.addWeeks)(currentDate, step);\n currentDate.setHours(15);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekendOfInterval = eachWeekendOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./eachDayOfInterval.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link eachWeekendOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekendOfInterval} function result type.\n */\n\n/**\n * @name eachWeekendOfInterval\n * @category Interval Helpers\n * @summary List all the Saturdays and Sundays in the given date interval.\n *\n * @description\n * Get all the Saturdays and Sundays in the given date interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The given interval\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given date interval\n * const result = eachWeekendOfInterval({\n * start: new Date(2018, 8, 17),\n * end: new Date(2018, 8, 30)\n * })\n * //=> [\n * // Sat Sep 22 2018 00:00:00,\n * // Sun Sep 23 2018 00:00:00,\n * // Sat Sep 29 2018 00:00:00,\n * // Sun Sep 30 2018 00:00:00\n * // ]\n */\nfunction eachWeekendOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const dateInterval = (0, _index3.eachDayOfInterval)({ start, end }, options);\n const weekends = [];\n let index = 0;\n while (index < dateInterval.length) {\n const date = dateInterval[index++];\n if ((0, _index4.isWeekend)(date))\n weekends.push((0, _index2.constructFrom)(start, date));\n }\n return weekends;\n}\n", "\"use strict\";\nexports.startOfMonth = startOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMonth} function options.\n */\n\n/**\n * @name startOfMonth\n * @category Month Helpers\n * @summary Return the start of a month for the given date.\n *\n * @description\n * Return the start of a month for the given date. The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments.\n * Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed,\n * or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a month\n *\n * @example\n * // The start of a month for 2 September 2014 11:55:00:\n * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachWeekendOfMonth = eachWeekendOfMonth;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\n\n/**\n * The {@link eachWeekendOfMonth} function options.\n */\n\n/**\n * @name eachWeekendOfMonth\n * @category Month Helpers\n * @summary List all the Saturdays and Sundays in the given month.\n *\n * @description\n * Get all the Saturdays and Sundays in the given month.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given month\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given month\n * const result = eachWeekendOfMonth(new Date(2022, 1, 1))\n * //=> [\n * // Sat Feb 05 2022 00:00:00,\n * // Sun Feb 06 2022 00:00:00,\n * // Sat Feb 12 2022 00:00:00,\n * // Sun Feb 13 2022 00:00:00,\n * // Sat Feb 19 2022 00:00:00,\n * // Sun Feb 20 2022 00:00:00,\n * // Sat Feb 26 2022 00:00:00,\n * // Sun Feb 27 2022 00:00:00\n * // ]\n */\nfunction eachWeekendOfMonth(date, options) {\n const start = (0, _index3.startOfMonth)(date, options);\n const end = (0, _index2.endOfMonth)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.endOfYear = endOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfYear} function options.\n */\n\n/**\n * @name endOfYear\n * @category Year Helpers\n * @summary Return the end of a year for the given date.\n *\n * @description\n * Return the end of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of a year\n *\n * @example\n * // The end of a year for 2 September 2014 11:55:00:\n * const result = endOfYear(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Wed Dec 31 2014 23:59:59.999\n */\nfunction endOfYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n _date.setFullYear(year + 1, 0, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.startOfYear = startOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfYear} function options.\n */\n\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a year\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nfunction startOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setFullYear(date_.getFullYear(), 0, 1);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.eachWeekendOfYear = eachWeekendOfYear;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfYear.cjs\");\nvar _index3 = require(\"./startOfYear.cjs\");\n\n/**\n * The {@link eachWeekendOfYear} function options.\n */\n\n/**\n * @name eachWeekendOfYear\n * @category Year Helpers\n * @summary List all the Saturdays and Sundays in the year.\n *\n * @description\n * Get all the Saturdays and Sundays in the year.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given year\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the year\n * const result = eachWeekendOfYear(new Date(2020, 1, 1))\n * //=> [\n * // Sat Jan 03 2020 00:00:00,\n * // Sun Jan 04 2020 00:00:00,\n * // ...\n * // Sun Dec 27 2020 00:00:00\n * // ]\n * ]\n */\nfunction eachWeekendOfYear(date, options) {\n const start = (0, _index3.startOfYear)(date, options);\n const end = (0, _index2.endOfYear)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.eachYearOfInterval = eachYearOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachYearOfInterval} function options.\n */\n\n/**\n * The {@link eachYearOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachYearOfInterval\n * @category Interval Helpers\n * @summary Return the array of yearly timestamps within the specified time interval.\n *\n * @description\n * Return the array of yearly timestamps within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of yearly timestamps from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each year between 6 February 2014 and 10 August 2017:\n * const result = eachYearOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2017, 7, 10)\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Thu Jan 01 2015 00:00:00,\n * // Fri Jan 01 2016 00:00:00,\n * // Sun Jan 01 2017 00:00:00\n * // ]\n */\nfunction eachYearOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setMonth(0, 1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setFullYear(date.getFullYear() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.endOfDecade = endOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDecade} function options.\n */\n\n/**\n * @name endOfDecade\n * @category Decade Helpers\n * @summary Return the end of a decade for the given date.\n *\n * @description\n * Return the end of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a decade\n *\n * @example\n * // The end of a decade for 12 May 1984 00:00:00:\n * const result = endOfDecade(new Date(1984, 4, 12, 00, 00, 00))\n * //=> Dec 31 1989 23:59:59.999\n */\nfunction endOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 11, 31);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfHour = endOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfHour} function options.\n */\n\n/**\n * @name endOfHour\n * @category Hour Helpers\n * @summary Return the end of an hour for the given date.\n *\n * @description\n * Return the end of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an hour\n *\n * @example\n * // The end of an hour for 2 September 2014 11:55:00:\n * const result = endOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:59:59.999\n */\nfunction endOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfWeek = endOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfWeek} function options.\n */\n\n/**\n * @name endOfWeek\n * @category Week Helpers\n * @summary Return the end of a week for the given date.\n *\n * @description\n * Return the end of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a week\n *\n * @example\n * // The end of a week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sat Sep 06 2014 23:59:59.999\n *\n * @example\n * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setDate(_date.getDate() + diff);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfISOWeek = endOfISOWeek;\nvar _index = require(\"./endOfWeek.cjs\");\n\n/**\n * The {@link endOfISOWeek} function options.\n */\n\n/**\n * @name endOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the end of an ISO week for the given date.\n *\n * @description\n * Return the end of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week\n *\n * @example\n * // The end of an ISO week for 2 September 2014 11:55:00:\n * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfISOWeek(date, options) {\n return (0, _index.endOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.endOfISOWeekYear = endOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link endOfISOWeekYear} function options.\n */\n\n/**\n * @name endOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the end of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the end of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The end of an ISO week-numbering year for 2 July 2005:\n * const result = endOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 23:59:59.999\n */\nfunction endOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(\n options?.in || date,\n 0,\n );\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const _date = (0, _index3.startOfISOWeek)(fourthOfJanuaryOfNextYear, options);\n _date.setMilliseconds(_date.getMilliseconds() - 1);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMinute = endOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMinute} function options.\n */\n\n/**\n * @name endOfMinute\n * @category Minute Helpers\n * @summary Return the end of a minute for the given date.\n *\n * @description\n * Return the end of a minute for the given date.\n * The result will be in the local timezone or the provided context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a minute\n *\n * @example\n * // The end of a minute for 1 December 2014 22:15:45.400:\n * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:59.999\n */\nfunction endOfMinute(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfQuarter = endOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfQuarter} function options.\n */\n\n/**\n * @name endOfQuarter\n * @category Quarter Helpers\n * @summary Return the end of a year quarter for the given date.\n *\n * @description\n * Return the end of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a quarter\n *\n * @example\n * // The end of a quarter for 2 September 2014 11:55:00:\n * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n _date.setMonth(month, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfSecond = endOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfSecond} function options.\n */\n\n/**\n * @name endOfSecond\n * @category Second Helpers\n * @summary Return the end of a second for the given date.\n *\n * @description\n * Return the end of a second for the given date.\n * The result will be in the local timezone if no `in` option is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a second\n *\n * @example\n * // The end of a second for 1 December 2014 22:15:45.400:\n * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.999\n */\nfunction endOfSecond(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfToday = endOfToday;\nvar _index = require(\"./endOfDay.cjs\");\n\n/**\n * The {@link endOfToday} function options.\n */\n\n/**\n * @name endOfToday\n * @category Day Helpers\n * @summary Return the end of today.\n * @pure false\n *\n * @description\n * Return the end of today.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n *\n * @returns The end of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfToday()\n * //=> Mon Oct 6 2014 23:59:59.999\n */\nfunction endOfToday(options) {\n return (0, _index.endOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.endOfTomorrow = endOfTomorrow;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfTomorrow} function options.\n */\n\n/**\n * @name endOfTomorrow\n * @category Day Helpers\n * @summary Return the end of tomorrow.\n * @pure false\n *\n * @description\n * Return the end of tomorrow.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n * @returns The end of tomorrow\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfTomorrow()\n * //=> Tue Oct 7 2014 23:59:59.999\n */\nfunction endOfTomorrow(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day + 1);\n date.setHours(23, 59, 59, 999);\n return options?.in ? options.in(date) : date;\n}\n", "\"use strict\";\nexports.endOfYesterday = endOfYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfYesterday} function options.\n */\n\n/**\n * @name endOfYesterday\n * @category Day Helpers\n * @summary Return the end of yesterday.\n * @pure false\n *\n * @description\n * Return the end of yesterday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @returns The end of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfYesterday()\n * //=> Sun Oct 5 2014 23:59:59.999\n */\nfunction endOfYesterday(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 1);\n date.setHours(23, 59, 59, 999);\n return date;\n}\n", "\"use strict\";\nexports.formatDistance = void 0;\n\nconst formatDistanceLocale = {\n lessThanXSeconds: {\n one: \"less than a second\",\n other: \"less than {{count}} seconds\",\n },\n\n xSeconds: {\n one: \"1 second\",\n other: \"{{count}} seconds\",\n },\n\n halfAMinute: \"half a minute\",\n\n lessThanXMinutes: {\n one: \"less than a minute\",\n other: \"less than {{count}} minutes\",\n },\n\n xMinutes: {\n one: \"1 minute\",\n other: \"{{count}} minutes\",\n },\n\n aboutXHours: {\n one: \"about 1 hour\",\n other: \"about {{count}} hours\",\n },\n\n xHours: {\n one: \"1 hour\",\n other: \"{{count}} hours\",\n },\n\n xDays: {\n one: \"1 day\",\n other: \"{{count}} days\",\n },\n\n aboutXWeeks: {\n one: \"about 1 week\",\n other: \"about {{count}} weeks\",\n },\n\n xWeeks: {\n one: \"1 week\",\n other: \"{{count}} weeks\",\n },\n\n aboutXMonths: {\n one: \"about 1 month\",\n other: \"about {{count}} months\",\n },\n\n xMonths: {\n one: \"1 month\",\n other: \"{{count}} months\",\n },\n\n aboutXYears: {\n one: \"about 1 year\",\n other: \"about {{count}} years\",\n },\n\n xYears: {\n one: \"1 year\",\n other: \"{{count}} years\",\n },\n\n overXYears: {\n one: \"over 1 year\",\n other: \"over {{count}} years\",\n },\n\n almostXYears: {\n one: \"almost 1 year\",\n other: \"almost {{count}} years\",\n },\n};\n\nconst formatDistance = (token, count, options) => {\n let result;\n\n const tokenValue = formatDistanceLocale[token];\n if (typeof tokenValue === \"string\") {\n result = tokenValue;\n } else if (count === 1) {\n result = tokenValue.one;\n } else {\n result = tokenValue.other.replace(\"{{count}}\", count.toString());\n }\n\n if (options?.addSuffix) {\n if (options.comparison && options.comparison > 0) {\n return \"in \" + result;\n } else {\n return result + \" ago\";\n }\n }\n\n return result;\n};\nexports.formatDistance = formatDistance;\n", "\"use strict\";\nexports.buildFormatLongFn = buildFormatLongFn;\n\nfunction buildFormatLongFn(args) {\n return (options = {}) => {\n // TODO: Remove String()\n const width = options.width ? String(options.width) : args.defaultWidth;\n const format = args.formats[width] || args.formats[args.defaultWidth];\n return format;\n };\n}\n", "\"use strict\";\nexports.formatLong = void 0;\nvar _index = require(\"../../_lib/buildFormatLongFn.cjs\");\n\nconst dateFormats = {\n full: \"EEEE, MMMM do, y\",\n long: \"MMMM do, y\",\n medium: \"MMM d, y\",\n short: \"MM/dd/yyyy\",\n};\n\nconst timeFormats = {\n full: \"h:mm:ss a zzzz\",\n long: \"h:mm:ss a z\",\n medium: \"h:mm:ss a\",\n short: \"h:mm a\",\n};\n\nconst dateTimeFormats = {\n full: \"{{date}} 'at' {{time}}\",\n long: \"{{date}} 'at' {{time}}\",\n medium: \"{{date}}, {{time}}\",\n short: \"{{date}}, {{time}}\",\n};\n\nconst formatLong = (exports.formatLong = {\n date: (0, _index.buildFormatLongFn)({\n formats: dateFormats,\n defaultWidth: \"full\",\n }),\n\n time: (0, _index.buildFormatLongFn)({\n formats: timeFormats,\n defaultWidth: \"full\",\n }),\n\n dateTime: (0, _index.buildFormatLongFn)({\n formats: dateTimeFormats,\n defaultWidth: \"full\",\n }),\n});\n", "\"use strict\";\nexports.formatRelative = void 0;\n\nconst formatRelativeLocale = {\n lastWeek: \"'last' eeee 'at' p\",\n yesterday: \"'yesterday at' p\",\n today: \"'today at' p\",\n tomorrow: \"'tomorrow at' p\",\n nextWeek: \"eeee 'at' p\",\n other: \"P\",\n};\n\nconst formatRelative = (token, _date, _baseDate, _options) =>\n formatRelativeLocale[token];\nexports.formatRelative = formatRelative;\n", "\"use strict\";\nexports.buildLocalizeFn = buildLocalizeFn;\n\n/**\n * The localize function argument callback which allows to convert raw value to\n * the actual type.\n *\n * @param value - The value to convert\n *\n * @returns The converted value\n */\n\n/**\n * The map of localized values for each width.\n */\n\n/**\n * The index type of the locale unit value. It types conversion of units of\n * values that don't start at 0 (i.e. quarters).\n */\n\n/**\n * Converts the unit value to the tuple of values.\n */\n\n/**\n * The tuple of localized era values. The first element represents BC,\n * the second element represents AD.\n */\n\n/**\n * The tuple of localized quarter values. The first element represents Q1.\n */\n\n/**\n * The tuple of localized day values. The first element represents Sunday.\n */\n\n/**\n * The tuple of localized month values. The first element represents January.\n */\n\nfunction buildLocalizeFn(args) {\n return (value, options) => {\n const context = options?.context ? String(options.context) : \"standalone\";\n\n let valuesArray;\n if (context === \"formatting\" && args.formattingValues) {\n const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;\n const width = options?.width ? String(options.width) : defaultWidth;\n\n valuesArray =\n args.formattingValues[width] || args.formattingValues[defaultWidth];\n } else {\n const defaultWidth = args.defaultWidth;\n const width = options?.width ? String(options.width) : args.defaultWidth;\n\n valuesArray = args.values[width] || args.values[defaultWidth];\n }\n const index = args.argumentCallback ? args.argumentCallback(value) : value;\n\n // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!\n return valuesArray[index];\n };\n}\n", "\"use strict\";\nexports.localize = void 0;\nvar _index = require(\"../../_lib/buildLocalizeFn.cjs\");\n\nconst eraValues = {\n narrow: [\"B\", \"A\"],\n abbreviated: [\"BC\", \"AD\"],\n wide: [\"Before Christ\", \"Anno Domini\"],\n};\n\nconst quarterValues = {\n narrow: [\"1\", \"2\", \"3\", \"4\"],\n abbreviated: [\"Q1\", \"Q2\", \"Q3\", \"Q4\"],\n wide: [\"1st quarter\", \"2nd quarter\", \"3rd quarter\", \"4th quarter\"],\n};\n\n// Note: in English, the names of days of the week and months are capitalized.\n// If you are making a new locale based on this one, check if the same is true for the language you're working on.\n// Generally, formatted dates should look like they are in the middle of a sentence,\n// e.g. in Spanish language the weekdays and months should be in the lowercase.\nconst monthValues = {\n narrow: [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"],\n abbreviated: [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ],\n\n wide: [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n ],\n};\n\nconst dayValues = {\n narrow: [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"],\n short: [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"],\n abbreviated: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n wide: [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n ],\n};\n\nconst dayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n};\n\nconst formattingDayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n};\n\nconst ordinalNumber = (dirtyNumber, _options) => {\n const number = Number(dirtyNumber);\n\n // If ordinal numbers depend on context, for example,\n // if they are different for different grammatical genders,\n // use `options.unit`.\n //\n // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',\n // 'day', 'hour', 'minute', 'second'.\n\n const rem100 = number % 100;\n if (rem100 > 20 || rem100 < 10) {\n switch (rem100 % 10) {\n case 1:\n return number + \"st\";\n case 2:\n return number + \"nd\";\n case 3:\n return number + \"rd\";\n }\n }\n return number + \"th\";\n};\n\nconst localize = (exports.localize = {\n ordinalNumber,\n\n era: (0, _index.buildLocalizeFn)({\n values: eraValues,\n defaultWidth: \"wide\",\n }),\n\n quarter: (0, _index.buildLocalizeFn)({\n values: quarterValues,\n defaultWidth: \"wide\",\n argumentCallback: (quarter) => quarter - 1,\n }),\n\n month: (0, _index.buildLocalizeFn)({\n values: monthValues,\n defaultWidth: \"wide\",\n }),\n\n day: (0, _index.buildLocalizeFn)({\n values: dayValues,\n defaultWidth: \"wide\",\n }),\n\n dayPeriod: (0, _index.buildLocalizeFn)({\n values: dayPeriodValues,\n defaultWidth: \"wide\",\n formattingValues: formattingDayPeriodValues,\n defaultFormattingWidth: \"wide\",\n }),\n});\n", "\"use strict\";\nexports.buildMatchFn = buildMatchFn;\n\nfunction buildMatchFn(args) {\n return (string, options = {}) => {\n const width = options.width;\n\n const matchPattern =\n (width && args.matchPatterns[width]) ||\n args.matchPatterns[args.defaultMatchWidth];\n const matchResult = string.match(matchPattern);\n\n if (!matchResult) {\n return null;\n }\n const matchedString = matchResult[0];\n\n const parsePatterns =\n (width && args.parsePatterns[width]) ||\n args.parsePatterns[args.defaultParseWidth];\n\n const key = Array.isArray(parsePatterns)\n ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))\n : // [TODO] -- I challenge you to fix the type\n findKey(parsePatterns, (pattern) => pattern.test(matchedString));\n\n let value;\n\n value = args.valueCallback ? args.valueCallback(key) : key;\n value = options.valueCallback\n ? // [TODO] -- I challenge you to fix the type\n options.valueCallback(value)\n : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n\nfunction findKey(object, predicate) {\n for (const key in object) {\n if (\n Object.prototype.hasOwnProperty.call(object, key) &&\n predicate(object[key])\n ) {\n return key;\n }\n }\n return undefined;\n}\n\nfunction findIndex(array, predicate) {\n for (let key = 0; key < array.length; key++) {\n if (predicate(array[key])) {\n return key;\n }\n }\n return undefined;\n}\n", "\"use strict\";\nexports.buildMatchPatternFn = buildMatchPatternFn;\n\nfunction buildMatchPatternFn(args) {\n return (string, options = {}) => {\n const matchResult = string.match(args.matchPattern);\n if (!matchResult) return null;\n const matchedString = matchResult[0];\n\n const parseResult = string.match(args.parsePattern);\n if (!parseResult) return null;\n let value = args.valueCallback\n ? args.valueCallback(parseResult[0])\n : parseResult[0];\n\n // [TODO] I challenge you to fix the type\n value = options.valueCallback ? options.valueCallback(value) : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n", "\"use strict\";\nexports.match = void 0;\n\nvar _index = require(\"../../_lib/buildMatchFn.cjs\");\nvar _index2 = require(\"../../_lib/buildMatchPatternFn.cjs\");\n\nconst matchOrdinalNumberPattern = /^(\\d+)(th|st|nd|rd)?/i;\nconst parseOrdinalNumberPattern = /\\d+/i;\n\nconst matchEraPatterns = {\n narrow: /^(b|a)/i,\n abbreviated: /^(b\\.?\\s?c\\.?|b\\.?\\s?c\\.?\\s?e\\.?|a\\.?\\s?d\\.?|c\\.?\\s?e\\.?)/i,\n wide: /^(before christ|before common era|anno domini|common era)/i,\n};\nconst parseEraPatterns = {\n any: [/^b/i, /^(a|c)/i],\n};\n\nconst matchQuarterPatterns = {\n narrow: /^[1234]/i,\n abbreviated: /^q[1234]/i,\n wide: /^[1234](th|st|nd|rd)? quarter/i,\n};\nconst parseQuarterPatterns = {\n any: [/1/i, /2/i, /3/i, /4/i],\n};\n\nconst matchMonthPatterns = {\n narrow: /^[jfmasond]/i,\n abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,\n wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,\n};\nconst parseMonthPatterns = {\n narrow: [\n /^j/i,\n /^f/i,\n /^m/i,\n /^a/i,\n /^m/i,\n /^j/i,\n /^j/i,\n /^a/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n\n any: [\n /^ja/i,\n /^f/i,\n /^mar/i,\n /^ap/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^au/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n};\n\nconst matchDayPatterns = {\n narrow: /^[smtwf]/i,\n short: /^(su|mo|tu|we|th|fr|sa)/i,\n abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,\n wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,\n};\nconst parseDayPatterns = {\n narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],\n any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],\n};\n\nconst matchDayPeriodPatterns = {\n narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,\n any: /^([ap]\\.?\\s?m\\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,\n};\nconst parseDayPeriodPatterns = {\n any: {\n am: /^a/i,\n pm: /^p/i,\n midnight: /^mi/i,\n noon: /^no/i,\n morning: /morning/i,\n afternoon: /afternoon/i,\n evening: /evening/i,\n night: /night/i,\n },\n};\n\nconst match = (exports.match = {\n ordinalNumber: (0, _index2.buildMatchPatternFn)({\n matchPattern: matchOrdinalNumberPattern,\n parsePattern: parseOrdinalNumberPattern,\n valueCallback: (value) => parseInt(value, 10),\n }),\n\n era: (0, _index.buildMatchFn)({\n matchPatterns: matchEraPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseEraPatterns,\n defaultParseWidth: \"any\",\n }),\n\n quarter: (0, _index.buildMatchFn)({\n matchPatterns: matchQuarterPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseQuarterPatterns,\n defaultParseWidth: \"any\",\n valueCallback: (index) => index + 1,\n }),\n\n month: (0, _index.buildMatchFn)({\n matchPatterns: matchMonthPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseMonthPatterns,\n defaultParseWidth: \"any\",\n }),\n\n day: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseDayPatterns,\n defaultParseWidth: \"any\",\n }),\n\n dayPeriod: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPeriodPatterns,\n defaultMatchWidth: \"any\",\n parsePatterns: parseDayPeriodPatterns,\n defaultParseWidth: \"any\",\n }),\n});\n", "\"use strict\";\nexports.enUS = void 0;\nvar _index = require(\"./en-US/_lib/formatDistance.cjs\");\nvar _index2 = require(\"./en-US/_lib/formatLong.cjs\");\nvar _index3 = require(\"./en-US/_lib/formatRelative.cjs\");\nvar _index4 = require(\"./en-US/_lib/localize.cjs\");\nvar _index5 = require(\"./en-US/_lib/match.cjs\");\n\n/**\n * @category Locales\n * @summary English locale (United States).\n * @language English\n * @iso-639-2 eng\n * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)\n * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)\n */\nconst enUS = (exports.enUS = {\n code: \"en-US\",\n formatDistance: _index.formatDistance,\n formatLong: _index2.formatLong,\n formatRelative: _index3.formatRelative,\n localize: _index4.localize,\n match: _index5.match,\n options: {\n weekStartsOn: 0 /* Sunday */,\n firstWeekContainsDate: 1,\n },\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"defaultLocale\", {\n enumerable: true,\n get: function () {\n return _index.enUS;\n },\n});\nvar _index = require(\"../locale/en-US.cjs\");\n", "\"use strict\";\nexports.getDayOfYear = getDayOfYear;\nvar _index = require(\"./differenceInCalendarDays.cjs\");\nvar _index2 = require(\"./startOfYear.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDayOfYear} function options.\n */\n\n/**\n * @name getDayOfYear\n * @category Day Helpers\n * @summary Get the day of the year of the given date.\n *\n * @description\n * Get the day of the year of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of year\n *\n * @example\n * // Which day of the year is 2 July 2014?\n * const result = getDayOfYear(new Date(2014, 6, 2))\n * //=> 183\n */\nfunction getDayOfYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const diff = (0, _index.differenceInCalendarDays)(\n _date,\n (0, _index2.startOfYear)(_date),\n );\n const dayOfYear = diff + 1;\n return dayOfYear;\n}\n", "\"use strict\";\nexports.getISOWeek = getISOWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeek} function options.\n */\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The ISO week\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nfunction getISOWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfISOWeek)(_date) -\n +(0, _index3.startOfISOWeekYear)(_date);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.getWeekYear = getWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./startOfWeek.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekYear} function options.\n */\n\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The local week-numbering year\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nfunction getWeekYear(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const firstWeekOfNextYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n firstWeekOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index3.startOfWeek)(\n firstWeekOfNextYear,\n options,\n );\n\n const firstWeekOfThisYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n firstWeekOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index3.startOfWeek)(\n firstWeekOfThisYear,\n options,\n );\n\n if (+_date >= +startOfNextYear) {\n return year + 1;\n } else if (+_date >= +startOfThisYear) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.startOfWeekYear = startOfWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./getWeekYear.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfWeekYear} function options.\n */\n\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week-numbering year\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfWeekYear(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const year = (0, _index3.getWeekYear)(date, options);\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n const _date = (0, _index4.startOfWeek)(firstWeek, options);\n return _date;\n}\n", "\"use strict\";\nexports.getWeek = getWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\nvar _index3 = require(\"./startOfWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeek} function options.\n */\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The week\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> 53\n */\nfunction getWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfWeek)(_date, options) -\n +(0, _index3.startOfWeekYear)(_date, options);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.addLeadingZeros = addLeadingZeros;\nfunction addLeadingZeros(number, targetLength) {\n const sign = number < 0 ? \"-\" : \"\";\n const output = Math.abs(number).toString().padStart(targetLength, \"0\");\n return sign + output;\n}\n", "\"use strict\";\nexports.lightFormatters = void 0;\nvar _index = require(\"../addLeadingZeros.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | |\n * | d | Day of month | D | |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | m | Minute | M | Month |\n * | s | Second | S | Fraction of second |\n * | y | Year (abs) | Y | |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n */\n\nconst lightFormatters = (exports.lightFormatters = {\n // Year\n y(date, token) {\n // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens\n // | Year | y | yy | yyy | yyyy | yyyyy |\n // |----------|-------|----|-------|-------|-------|\n // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\n\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return (0, _index.addLeadingZeros)(\n token === \"yy\" ? year % 100 : year,\n token.length,\n );\n },\n\n // Month\n M(date, token) {\n const month = date.getMonth();\n return token === \"M\"\n ? String(month + 1)\n : (0, _index.addLeadingZeros)(month + 1, 2);\n },\n\n // Day of the month\n d(date, token) {\n return (0, _index.addLeadingZeros)(date.getDate(), token.length);\n },\n\n // AM or PM\n a(date, token) {\n const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return dayPeriodEnumValue.toUpperCase();\n case \"aaa\":\n return dayPeriodEnumValue;\n case \"aaaaa\":\n return dayPeriodEnumValue[0];\n case \"aaaa\":\n default:\n return dayPeriodEnumValue === \"am\" ? \"a.m.\" : \"p.m.\";\n }\n },\n\n // Hour [1-12]\n h(date, token) {\n return (0, _index.addLeadingZeros)(\n date.getHours() % 12 || 12,\n token.length,\n );\n },\n\n // Hour [0-23]\n H(date, token) {\n return (0, _index.addLeadingZeros)(date.getHours(), token.length);\n },\n\n // Minute\n m(date, token) {\n return (0, _index.addLeadingZeros)(date.getMinutes(), token.length);\n },\n\n // Second\n s(date, token) {\n return (0, _index.addLeadingZeros)(date.getSeconds(), token.length);\n },\n\n // Fraction of second\n S(date, token) {\n const numberOfDigits = token.length;\n const milliseconds = date.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, numberOfDigits - 3),\n );\n return (0, _index.addLeadingZeros)(fractionalSeconds, token.length);\n },\n});\n", "\"use strict\";\nexports.formatters = void 0;\nvar _index = require(\"../../getDayOfYear.cjs\");\nvar _index2 = require(\"../../getISOWeek.cjs\");\nvar _index3 = require(\"../../getISOWeekYear.cjs\");\nvar _index4 = require(\"../../getWeek.cjs\");\nvar _index5 = require(\"../../getWeekYear.cjs\");\n\nvar _index6 = require(\"../addLeadingZeros.cjs\");\nvar _index7 = require(\"./lightFormatters.cjs\");\n\nconst dayPeriodEnum = {\n am: \"am\",\n pm: \"pm\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n};\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O | Timezone (GMT) |\n * | p! | Long localized time | P! | Long localized date |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n * - `P` is long localized date format\n * - `p` is long localized time format\n */\n\nconst formatters = (exports.formatters = {\n // Era\n G: function (date, token, localize) {\n const era = date.getFullYear() > 0 ? 1 : 0;\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return localize.era(era, { width: \"abbreviated\" });\n // A, B\n case \"GGGGG\":\n return localize.era(era, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return localize.era(era, { width: \"wide\" });\n }\n },\n\n // Year\n y: function (date, token, localize) {\n // Ordinal number\n if (token === \"yo\") {\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return localize.ordinalNumber(year, { unit: \"year\" });\n }\n\n return _index7.lightFormatters.y(date, token);\n },\n\n // Local week-numbering year\n Y: function (date, token, localize, options) {\n const signedWeekYear = (0, _index5.getWeekYear)(date, options);\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;\n\n // Two digit year\n if (token === \"YY\") {\n const twoDigitYear = weekYear % 100;\n return (0, _index6.addLeadingZeros)(twoDigitYear, 2);\n }\n\n // Ordinal number\n if (token === \"Yo\") {\n return localize.ordinalNumber(weekYear, { unit: \"year\" });\n }\n\n // Padding\n return (0, _index6.addLeadingZeros)(weekYear, token.length);\n },\n\n // ISO week-numbering year\n R: function (date, token) {\n const isoWeekYear = (0, _index3.getISOWeekYear)(date);\n\n // Padding\n return (0, _index6.addLeadingZeros)(isoWeekYear, token.length);\n },\n\n // Extended year. This is a single number designating the year of this calendar system.\n // The main difference between `y` and `u` localizers are B.C. years:\n // | Year | `y` | `u` |\n // |------|-----|-----|\n // | AC 1 | 1 | 1 |\n // | BC 1 | 1 | 0 |\n // | BC 2 | 2 | -1 |\n // Also `yy` always returns the last two digits of a year,\n // while `uu` pads single digit years to 2 characters and returns other years unchanged.\n u: function (date, token) {\n const year = date.getFullYear();\n return (0, _index6.addLeadingZeros)(year, token.length);\n },\n\n // Quarter\n Q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"QQ\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone quarter\n q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"qq\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // Month\n M: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n case \"M\":\n case \"MM\":\n return _index7.lightFormatters.M(date, token);\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // J, F, ..., D\n case \"MMMMM\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return localize.month(month, { width: \"wide\", context: \"formatting\" });\n }\n },\n\n // Stand-alone month\n L: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return String(month + 1);\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _index6.addLeadingZeros)(month + 1, 2);\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // J, F, ..., D\n case \"LLLLL\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return localize.month(month, { width: \"wide\", context: \"standalone\" });\n }\n },\n\n // Local week of year\n w: function (date, token, localize, options) {\n const week = (0, _index4.getWeek)(date, options);\n\n if (token === \"wo\") {\n return localize.ordinalNumber(week, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(week, token.length);\n },\n\n // ISO week of year\n I: function (date, token, localize) {\n const isoWeek = (0, _index2.getISOWeek)(date);\n\n if (token === \"Io\") {\n return localize.ordinalNumber(isoWeek, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(isoWeek, token.length);\n },\n\n // Day of the month\n d: function (date, token, localize) {\n if (token === \"do\") {\n return localize.ordinalNumber(date.getDate(), { unit: \"date\" });\n }\n\n return _index7.lightFormatters.d(date, token);\n },\n\n // Day of year\n D: function (date, token, localize) {\n const dayOfYear = (0, _index.getDayOfYear)(date);\n\n if (token === \"Do\") {\n return localize.ordinalNumber(dayOfYear, { unit: \"dayOfYear\" });\n }\n\n return (0, _index6.addLeadingZeros)(dayOfYear, token.length);\n },\n\n // Day of week\n E: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"EEEEE\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"EEEE\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Local day of week\n e: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (Nth day of week with current locale or weekStartsOn)\n case \"e\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"ee\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, 2);\n // 1st, 2nd, ..., 7th\n case \"eo\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"eee\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"eeeee\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"eeee\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone local day of week\n c: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (same as in `e`)\n case \"c\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"cc\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, token.length);\n // 1st, 2nd, ..., 7th\n case \"co\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"ccc\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // T\n case \"ccccc\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"standalone\",\n });\n // Tuesday\n case \"cccc\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // ISO day of week\n i: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;\n switch (token) {\n // 2\n case \"i\":\n return String(isoDayOfWeek);\n // 02\n case \"ii\":\n return (0, _index6.addLeadingZeros)(isoDayOfWeek, token.length);\n // 2nd\n case \"io\":\n return localize.ordinalNumber(isoDayOfWeek, { unit: \"day\" });\n // Tue\n case \"iii\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"iiiii\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"iiiiii\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"iiii\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM or PM\n a: function (date, token, localize) {\n const hours = date.getHours();\n const dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"aaa\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"aaaaa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM, PM, midnight, noon\n b: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours === 12) {\n dayPeriodEnumValue = dayPeriodEnum.noon;\n } else if (hours === 0) {\n dayPeriodEnumValue = dayPeriodEnum.midnight;\n } else {\n dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n }\n\n switch (token) {\n case \"b\":\n case \"bb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"bbb\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"bbbbb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // in the morning, in the afternoon, in the evening, at night\n B: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours >= 17) {\n dayPeriodEnumValue = dayPeriodEnum.evening;\n } else if (hours >= 12) {\n dayPeriodEnumValue = dayPeriodEnum.afternoon;\n } else if (hours >= 4) {\n dayPeriodEnumValue = dayPeriodEnum.morning;\n } else {\n dayPeriodEnumValue = dayPeriodEnum.night;\n }\n\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"BBBBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Hour [1-12]\n h: function (date, token, localize) {\n if (token === \"ho\") {\n let hours = date.getHours() % 12;\n if (hours === 0) hours = 12;\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.h(date, token);\n },\n\n // Hour [0-23]\n H: function (date, token, localize) {\n if (token === \"Ho\") {\n return localize.ordinalNumber(date.getHours(), { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.H(date, token);\n },\n\n // Hour [0-11]\n K: function (date, token, localize) {\n const hours = date.getHours() % 12;\n\n if (token === \"Ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Hour [1-24]\n k: function (date, token, localize) {\n let hours = date.getHours();\n if (hours === 0) hours = 24;\n\n if (token === \"ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Minute\n m: function (date, token, localize) {\n if (token === \"mo\") {\n return localize.ordinalNumber(date.getMinutes(), { unit: \"minute\" });\n }\n\n return _index7.lightFormatters.m(date, token);\n },\n\n // Second\n s: function (date, token, localize) {\n if (token === \"so\") {\n return localize.ordinalNumber(date.getSeconds(), { unit: \"second\" });\n }\n\n return _index7.lightFormatters.s(date, token);\n },\n\n // Fraction of second\n S: function (date, token) {\n return _index7.lightFormatters.S(date, token);\n },\n\n // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n X: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n if (timezoneOffset === 0) {\n return \"Z\";\n }\n\n switch (token) {\n // Hours and optional minutes\n case \"X\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XX`\n case \"XXXX\":\n case \"XX\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XXX`\n case \"XXXXX\":\n case \"XXX\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n x: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Hours and optional minutes\n case \"x\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xx`\n case \"xxxx\":\n case \"xx\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xxx`\n case \"xxxxx\":\n case \"xxx\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (GMT)\n O: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"O\":\n case \"OO\":\n case \"OOO\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"OOOO\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (specific non-location)\n z: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"z\":\n case \"zz\":\n case \"zzz\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"zzzz\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Seconds timestamp\n t: function (date, token, _localize) {\n const timestamp = Math.trunc(+date / 1000);\n return (0, _index6.addLeadingZeros)(timestamp, token.length);\n },\n\n // Milliseconds timestamp\n T: function (date, token, _localize) {\n return (0, _index6.addLeadingZeros)(+date, token.length);\n },\n});\n\nfunction formatTimezoneShort(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = Math.trunc(absOffset / 60);\n const minutes = absOffset % 60;\n if (minutes === 0) {\n return sign + String(hours);\n }\n return (\n sign + String(hours) + delimiter + (0, _index6.addLeadingZeros)(minutes, 2)\n );\n}\n\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n if (offset % 60 === 0) {\n const sign = offset > 0 ? \"-\" : \"+\";\n return sign + (0, _index6.addLeadingZeros)(Math.abs(offset) / 60, 2);\n }\n return formatTimezone(offset, delimiter);\n}\n\nfunction formatTimezone(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = (0, _index6.addLeadingZeros)(Math.trunc(absOffset / 60), 2);\n const minutes = (0, _index6.addLeadingZeros)(absOffset % 60, 2);\n return sign + hours + delimiter + minutes;\n}\n", "\"use strict\";\nexports.longFormatters = void 0;\n\nconst dateLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"P\":\n return formatLong.date({ width: \"short\" });\n case \"PP\":\n return formatLong.date({ width: \"medium\" });\n case \"PPP\":\n return formatLong.date({ width: \"long\" });\n case \"PPPP\":\n default:\n return formatLong.date({ width: \"full\" });\n }\n};\n\nconst timeLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"p\":\n return formatLong.time({ width: \"short\" });\n case \"pp\":\n return formatLong.time({ width: \"medium\" });\n case \"ppp\":\n return formatLong.time({ width: \"long\" });\n case \"pppp\":\n default:\n return formatLong.time({ width: \"full\" });\n }\n};\n\nconst dateTimeLongFormatter = (pattern, formatLong) => {\n const matchResult = pattern.match(/(P+)(p+)?/) || [];\n const datePattern = matchResult[1];\n const timePattern = matchResult[2];\n\n if (!timePattern) {\n return dateLongFormatter(pattern, formatLong);\n }\n\n let dateTimeFormat;\n\n switch (datePattern) {\n case \"P\":\n dateTimeFormat = formatLong.dateTime({ width: \"short\" });\n break;\n case \"PP\":\n dateTimeFormat = formatLong.dateTime({ width: \"medium\" });\n break;\n case \"PPP\":\n dateTimeFormat = formatLong.dateTime({ width: \"long\" });\n break;\n case \"PPPP\":\n default:\n dateTimeFormat = formatLong.dateTime({ width: \"full\" });\n break;\n }\n\n return dateTimeFormat\n .replace(\"{{date}}\", dateLongFormatter(datePattern, formatLong))\n .replace(\"{{time}}\", timeLongFormatter(timePattern, formatLong));\n};\n\nconst longFormatters = (exports.longFormatters = {\n p: timeLongFormatter,\n P: dateTimeLongFormatter,\n});\n", "\"use strict\";\nexports.isProtectedDayOfYearToken = isProtectedDayOfYearToken;\nexports.isProtectedWeekYearToken = isProtectedWeekYearToken;\nexports.warnOrThrowProtectedError = warnOrThrowProtectedError;\nconst dayOfYearTokenRE = /^D+$/;\nconst weekYearTokenRE = /^Y+$/;\n\nconst throwTokens = [\"D\", \"DD\", \"YY\", \"YYYY\"];\n\nfunction isProtectedDayOfYearToken(token) {\n return dayOfYearTokenRE.test(token);\n}\n\nfunction isProtectedWeekYearToken(token) {\n return weekYearTokenRE.test(token);\n}\n\nfunction warnOrThrowProtectedError(token, format, input) {\n const _message = message(token, format, input);\n console.warn(_message);\n if (throwTokens.includes(token)) throw new RangeError(_message);\n}\n\nfunction message(token, format, input) {\n const subject = token[0] === \"Y\" ? \"years\" : \"days of the month\";\n return `Use \\`${token.toLowerCase()}\\` instead of \\`${token}\\` (in \\`${format}\\`) for formatting ${subject} to the input \\`${input}\\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;\n}\n", "\"use strict\";\nexports.format = exports.formatDate = format;\nObject.defineProperty(exports, \"formatters\", {\n enumerable: true,\n get: function () {\n return _index3.formatters;\n },\n});\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index4.longFormatters;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/format/formatters.cjs\");\nvar _index4 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index5 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index6 = require(\"./isValid.cjs\");\nvar _index7 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * The {@link format} function options.\n */\n\n/**\n * @name format\n * @alias formatDate\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may vary by locale.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era | G..GGG | AD, BC | |\n * | | GGGG | Anno Domini, Before Christ | 2 |\n * | | GGGGG | A, B | |\n * | Calendar year | y | 44, 1, 1900, 2017 | 5 |\n * | | yo | 44th, 1st, 0th, 17th | 5,7 |\n * | | yy | 44, 01, 00, 17 | 5 |\n * | | yyy | 044, 001, 1900, 2017 | 5 |\n * | | yyyy | 0044, 0001, 1900, 2017 | 5 |\n * | | yyyyy | ... | 3,5 |\n * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |\n * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |\n * | | YY | 44, 01, 00, 17 | 5,8 |\n * | | YYY | 044, 001, 1900, 2017 | 5 |\n * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |\n * | | YYYYY | ... | 3,5 |\n * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |\n * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |\n * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |\n * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |\n * | | RRRRR | ... | 3,5,7 |\n * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |\n * | | uu | -43, 01, 1900, 2017 | 5 |\n * | | uuu | -043, 001, 1900, 2017 | 5 |\n * | | uuuu | -0043, 0001, 1900, 2017 | 5 |\n * | | uuuuu | ... | 3,5 |\n * | Quarter (formatting) | Q | 1, 2, 3, 4 | |\n * | | Qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | QQ | 01, 02, 03, 04 | |\n * | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |\n * | | qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | qq | 01, 02, 03, 04 | |\n * | | qqq | Q1, Q2, Q3, Q4 | |\n * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | qqqqq | 1, 2, 3, 4 | 4 |\n * | Month (formatting) | M | 1, 2, ..., 12 | |\n * | | Mo | 1st, 2nd, ..., 12th | 7 |\n * | | MM | 01, 02, ..., 12 | |\n * | | MMM | Jan, Feb, ..., Dec | |\n * | | MMMM | January, February, ..., December | 2 |\n * | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | L | 1, 2, ..., 12 | |\n * | | Lo | 1st, 2nd, ..., 12th | 7 |\n * | | LL | 01, 02, ..., 12 | |\n * | | LLL | Jan, Feb, ..., Dec | |\n * | | LLLL | January, February, ..., December | 2 |\n * | | LLLLL | J, F, ..., D | |\n * | Local week of year | w | 1, 2, ..., 53 | |\n * | | wo | 1st, 2nd, ..., 53th | 7 |\n * | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | I | 1, 2, ..., 53 | 7 |\n * | | Io | 1st, 2nd, ..., 53th | 7 |\n * | | II | 01, 02, ..., 53 | 7 |\n * | Day of month | d | 1, 2, ..., 31 | |\n * | | do | 1st, 2nd, ..., 31st | 7 |\n * | | dd | 01, 02, ..., 31 | |\n * | Day of year | D | 1, 2, ..., 365, 366 | 9 |\n * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |\n * | | DD | 01, 02, ..., 365, 366 | 9 |\n * | | DDD | 001, 002, ..., 365, 366 | |\n * | | DDDD | ... | 3 |\n * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | EEEEE | M, T, W, T, F, S, S | |\n * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |\n * | | io | 1st, 2nd, ..., 7th | 7 |\n * | | ii | 01, 02, ..., 07 | 7 |\n * | | iii | Mon, Tue, Wed, ..., Sun | 7 |\n * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |\n * | | iiiii | M, T, W, T, F, S, S | 7 |\n * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |\n * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |\n * | | eo | 2nd, 3rd, ..., 1st | 7 |\n * | | ee | 02, 03, ..., 01 | |\n * | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | eeeee | M, T, W, T, F, S, S | |\n * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |\n * | | co | 2nd, 3rd, ..., 1st | 7 |\n * | | cc | 02, 03, ..., 01 | |\n * | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | ccccc | M, T, W, T, F, S, S | |\n * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | a..aa | AM, PM | |\n * | | aaa | am, pm | |\n * | | aaaa | a.m., p.m. | 2 |\n * | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |\n * | | bbb | am, pm, noon, midnight | |\n * | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | bbbbb | a, p, n, mi | |\n * | Flexible day period | B..BBB | at night, in the morning, ... | |\n * | | BBBB | at night, in the morning, ... | 2 |\n * | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |\n * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |\n * | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |\n * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |\n * | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |\n * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |\n * | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |\n * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |\n * | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | m | 0, 1, ..., 59 | |\n * | | mo | 0th, 1st, ..., 59th | 7 |\n * | | mm | 00, 01, ..., 59 | |\n * | Second | s | 0, 1, ..., 59 | |\n * | | so | 0th, 1st, ..., 59th | 7 |\n * | | ss | 00, 01, ..., 59 | |\n * | Fraction of second | S | 0, 1, ..., 9 | |\n * | | SS | 00, 01, ..., 99 | |\n * | | SSS | 000, 001, ..., 999 | |\n * | | SSSS | ... | 3 |\n * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |\n * | | XX | -0800, +0530, Z | |\n * | | XXX | -08:00, +05:30, Z | |\n * | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |\n * | | xx | -0800, +0530, +0000 | |\n * | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |\n * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |\n * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |\n * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |\n * | Seconds timestamp | t | 512969520 | 7 |\n * | | tt | ... | 3,7 |\n * | Milliseconds timestamp | T | 512969520900 | 7 |\n * | | TT | ... | 3,7 |\n * | Long localized date | P | 04/29/1453 | 7 |\n * | | PP | Apr 29, 1453 | 7 |\n * | | PPP | April 29th, 1453 | 7 |\n * | | PPPP | Friday, April 29th, 1453 | 2,7 |\n * | Long localized time | p | 12:00 AM | 7 |\n * | | pp | 12:00:00 AM | 7 |\n * | | ppp | 12:00:00 AM GMT+2 | 7 |\n * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |\n * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |\n * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |\n * | | PPPppp | April 29th, 1453 at ... | 7 |\n * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n * the output will be the same as default pattern for this unit, usually\n * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n * are marked with \"2\" in the last column of the table.\n *\n * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n * The output will be padded with zeros to match the length of the pattern.\n *\n * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` always returns the last two digits of a year,\n * while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n * | Year | `yy` | `uu` |\n * |------|------|------|\n * | 1 | 01 | 01 |\n * | 14 | 14 | 14 |\n * | 376 | 76 | 376 |\n * | 1453 | 53 | 1453 |\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)\n * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).\n *\n * 6. Specific non-location timezones are currently unavailable in `date-fns`,\n * so right now these tokens fall back to GMT timezones.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `t`: seconds timestamp\n * - `T`: milliseconds timestamp\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @param date - The original date\n * @param format - The string of tokens\n * @param options - An object with options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n * locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nfunction format(date, formatStr, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const originalDate = (0, _index7.toDate)(date, options?.in);\n\n if (!(0, _index6.isValid)(originalDate)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let parts = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter === \"p\" || firstCharacter === \"P\") {\n const longFormatter = _index4.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp)\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return { isToken: false, value: \"'\" };\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return { isToken: false, value: cleanEscapedString(substring) };\n }\n\n if (_index3.formatters[firstCharacter]) {\n return { isToken: true, value: substring };\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return { isToken: false, value: substring };\n });\n\n // invoke localize preprocessor (only for french locales at the moment)\n if (locale.localize.preprocessor) {\n parts = locale.localize.preprocessor(originalDate, parts);\n }\n\n const formatterOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n return parts\n .map((part) => {\n if (!part.isToken) return part.value;\n\n const token = part.value;\n\n if (\n (!options?.useAdditionalWeekYearTokens &&\n (0, _index5.isProtectedWeekYearToken)(token)) ||\n (!options?.useAdditionalDayOfYearTokens &&\n (0, _index5.isProtectedDayOfYearToken)(token))\n ) {\n (0, _index5.warnOrThrowProtectedError)(token, formatStr, String(date));\n }\n\n const formatter = _index3.formatters[token[0]];\n return formatter(originalDate, token, locale.localize, formatterOptions);\n })\n .join(\"\");\n}\n\nfunction cleanEscapedString(input) {\n const matched = input.match(escapedStringRegExp);\n\n if (!matched) {\n return input;\n }\n\n return matched[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.formatDistance = formatDistance;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index4 = require(\"./_lib/normalizeDates.cjs\");\nvar _index5 = require(\"./compareAsc.cjs\");\nvar _index6 = require(\"./constants.cjs\");\nvar _index7 = require(\"./differenceInMonths.cjs\");\nvar _index8 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link formatDistance} function options.\n */\n\n/**\n * @name formatDistance\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words.\n *\n * | Distance between dates | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance between dates | Result |\n * |------------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00, including seconds?\n * const result = formatDistance(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0),\n * { includeSeconds: true }\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> 'about 1 year ago'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistance(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const minutesInAlmostTwoDays = 2520;\n\n const comparison = (0, _index5.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) throw new RangeError(\"Invalid time value\");\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index4.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const seconds = (0, _index8.differenceInSeconds)(earlierDate_, laterDate_);\n const offsetInSeconds =\n ((0, _index3.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index3.getTimezoneOffsetInMilliseconds)(laterDate_)) /\n 1000;\n const minutes = Math.round((seconds - offsetInSeconds) / 60);\n let months;\n\n // 0 up to 2 mins\n if (minutes < 2) {\n if (options?.includeSeconds) {\n if (seconds < 5) {\n return locale.formatDistance(\"lessThanXSeconds\", 5, localizeOptions);\n } else if (seconds < 10) {\n return locale.formatDistance(\"lessThanXSeconds\", 10, localizeOptions);\n } else if (seconds < 20) {\n return locale.formatDistance(\"lessThanXSeconds\", 20, localizeOptions);\n } else if (seconds < 40) {\n return locale.formatDistance(\"halfAMinute\", 0, localizeOptions);\n } else if (seconds < 60) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", 1, localizeOptions);\n }\n } else {\n if (minutes === 0) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n }\n }\n\n // 2 mins up to 0.75 hrs\n } else if (minutes < 45) {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n\n // 0.75 hrs up to 1.5 hrs\n } else if (minutes < 90) {\n return locale.formatDistance(\"aboutXHours\", 1, localizeOptions);\n\n // 1.5 hrs up to 24 hrs\n } else if (minutes < _index6.minutesInDay) {\n const hours = Math.round(minutes / 60);\n return locale.formatDistance(\"aboutXHours\", hours, localizeOptions);\n\n // 1 day up to 1.75 days\n } else if (minutes < minutesInAlmostTwoDays) {\n return locale.formatDistance(\"xDays\", 1, localizeOptions);\n\n // 1.75 days up to 30 days\n } else if (minutes < _index6.minutesInMonth) {\n const days = Math.round(minutes / _index6.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 month up to 2 months\n } else if (minutes < _index6.minutesInMonth * 2) {\n months = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"aboutXMonths\", months, localizeOptions);\n }\n\n months = (0, _index7.differenceInMonths)(earlierDate_, laterDate_);\n\n // 2 months up to 12 months\n if (months < 12) {\n const nearestMonth = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"xMonths\", nearestMonth, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const monthsSinceStartOfYear = months % 12;\n const years = Math.trunc(months / 12);\n\n // N years up to 1 years 3 months\n if (monthsSinceStartOfYear < 3) {\n return locale.formatDistance(\"aboutXYears\", years, localizeOptions);\n\n // N years 3 months up to N years 9 months\n } else if (monthsSinceStartOfYear < 9) {\n return locale.formatDistance(\"overXYears\", years, localizeOptions);\n\n // N years 9 months up to N year 12 months\n } else {\n return locale.formatDistance(\"almostXYears\", years + 1, localizeOptions);\n }\n }\n}\n", "\"use strict\";\nexports.formatDistanceStrict = formatDistanceStrict;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index4 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index5 = require(\"./_lib/normalizeDates.cjs\");\nvar _index6 = require(\"./compareAsc.cjs\");\nvar _index7 = require(\"./constants.cjs\");\n\n/**\n * The {@link formatDistanceStrict} function options.\n */\n\n/**\n * The unit used to format the distance in {@link formatDistanceStrict}.\n */\n\n/**\n * @name formatDistanceStrict\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year'\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00?\n * const result = formatDistanceStrict(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> '1 year ago'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, in minutes?\n * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), {\n * unit: 'minute'\n * })\n * //=> '525600 minutes'\n *\n * @example\n * // What is the distance from 1 January 2015\n * // to 28 January 2015, in months, rounded up?\n * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> '1 jaro'\n */\n\nfunction formatDistanceStrict(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const comparison = (0, _index6.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index5.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const roundingMethod = (0, _index3.getRoundingMethod)(\n options?.roundingMethod ?? \"round\",\n );\n\n const milliseconds = earlierDate_.getTime() - laterDate_.getTime();\n const minutes = milliseconds / _index7.millisecondsInMinute;\n\n const timezoneOffset =\n (0, _index4.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index4.getTimezoneOffsetInMilliseconds)(laterDate_);\n\n // Use DST-normalized difference in minutes for years, months and days;\n // use regular difference in minutes for hours, minutes and seconds.\n const dstNormalizedMinutes =\n (milliseconds - timezoneOffset) / _index7.millisecondsInMinute;\n\n const defaultUnit = options?.unit;\n let unit;\n if (!defaultUnit) {\n if (minutes < 1) {\n unit = \"second\";\n } else if (minutes < 60) {\n unit = \"minute\";\n } else if (minutes < _index7.minutesInDay) {\n unit = \"hour\";\n } else if (dstNormalizedMinutes < _index7.minutesInMonth) {\n unit = \"day\";\n } else if (dstNormalizedMinutes < _index7.minutesInYear) {\n unit = \"month\";\n } else {\n unit = \"year\";\n }\n } else {\n unit = defaultUnit;\n }\n\n // 0 up to 60 seconds\n if (unit === \"second\") {\n const seconds = roundingMethod(milliseconds / 1000);\n return locale.formatDistance(\"xSeconds\", seconds, localizeOptions);\n\n // 1 up to 60 mins\n } else if (unit === \"minute\") {\n const roundedMinutes = roundingMethod(minutes);\n return locale.formatDistance(\"xMinutes\", roundedMinutes, localizeOptions);\n\n // 1 up to 24 hours\n } else if (unit === \"hour\") {\n const hours = roundingMethod(minutes / 60);\n return locale.formatDistance(\"xHours\", hours, localizeOptions);\n\n // 1 up to 30 days\n } else if (unit === \"day\") {\n const days = roundingMethod(dstNormalizedMinutes / _index7.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 up to 12 months\n } else if (unit === \"month\") {\n const months = roundingMethod(\n dstNormalizedMinutes / _index7.minutesInMonth,\n );\n return months === 12 && defaultUnit !== \"month\"\n ? locale.formatDistance(\"xYears\", 1, localizeOptions)\n : locale.formatDistance(\"xMonths\", months, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const years = roundingMethod(dstNormalizedMinutes / _index7.minutesInYear);\n return locale.formatDistance(\"xYears\", years, localizeOptions);\n }\n}\n", "\"use strict\";\nexports.formatDistanceToNow = formatDistanceToNow;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistance.cjs\");\n\n/**\n * The {@link formatDistanceToNow} function options.\n */\n\n/**\n * @name formatDistanceToNow\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given date and now in words.\n *\n * | Distance to now | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance to now | Result |\n * |---------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param date - The given date\n * @param options - The object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNow(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNow(\n * new Date(2015, 0, 1, 0, 0, 15),\n * {includeSeconds: true}\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNow(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in about 1 year'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 August 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNow(\n * new Date(2016, 7, 1),\n * {locale: eoLocale}\n * )\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistanceToNow(date, options) {\n return (0, _index2.formatDistance)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDistanceToNowStrict = formatDistanceToNowStrict;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistanceStrict.cjs\");\n\n/**\n * The {@link formatDistanceToNowStrict} function options.\n */\n\n/**\n * @name formatDistanceToNowStrict\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNowStrict(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNowStrict(\n * new Date(2015, 0, 1, 0, 0, 15)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in 1 year'\n *\n * @example\n * // If today is 28 January 2015,\n * // what is the distance to 1 January 2015, in months, rounded up??\n * const result = formatDistanceToNowStrict(new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {locale: eoLocale}\n * )\n * //=> '1 jaro'\n */\nfunction formatDistanceToNowStrict(date, options) {\n return (0, _index2.formatDistanceStrict)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDuration = formatDuration;\n\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * The {@link formatDuration} function options.\n */\n\nconst defaultFormat = [\n \"years\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n];\n\n/**\n * @name formatDuration\n * @category Common Helpers\n * @summary Formats a duration in human-readable format\n *\n * @description\n * Return human-readable duration string i.e. \"9 months 2 days\"\n *\n * @param duration - The duration to format\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @example\n * // Format full duration\n * formatDuration({\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> '2 years 9 months 1 week 7 days 5 hours 9 minutes 30 seconds'\n *\n * @example\n * // Format partial duration\n * formatDuration({ months: 9, days: 2 })\n * //=> '9 months 2 days'\n *\n * @example\n * // Customize the format\n * formatDuration(\n * {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * },\n * { format: ['months', 'weeks'] }\n * ) === '9 months 1 week'\n *\n * @example\n * // Customize the zeros presence\n * formatDuration({ years: 0, months: 9 })\n * //=> '9 months'\n * formatDuration({ years: 0, months: 9 }, { zero: true })\n * //=> '0 years 9 months'\n *\n * @example\n * // Customize the delimiter\n * formatDuration({ years: 2, months: 9, weeks: 3 }, { delimiter: ', ' })\n * //=> '2 years, 9 months, 3 weeks'\n */\nfunction formatDuration(duration, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const format = options?.format ?? defaultFormat;\n const zero = options?.zero ?? false;\n const delimiter = options?.delimiter ?? \" \";\n\n if (!locale.formatDistance) {\n return \"\";\n }\n\n const result = format\n .reduce((acc, unit) => {\n const token = `x${unit.replace(/(^.)/, (m) => m.toUpperCase())}`;\n const value = duration[unit];\n if (value !== undefined && (zero || duration[unit])) {\n return acc.concat(locale.formatDistance(token, value));\n }\n return acc;\n }, [])\n .join(delimiter);\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO = formatISO;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO} function options.\n */\n\n/**\n * @name formatISO\n * @category Common Helpers\n * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm).\n *\n * @description\n * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string (in local time zone)\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918T190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, date only:\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52Z'\n */\nfunction formatISO(date, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n if (isNaN(+date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n let tzOffset = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n // Add the timezone.\n const offset = date_.getTimezoneOffset();\n\n if (offset !== 0) {\n const absoluteOffset = Math.abs(offset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = offset < 0 ? \"+\" : \"-\";\n\n tzOffset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n tzOffset = \"Z\";\n }\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with 'T'\n const separator = result === \"\" ? \"\" : \"T\";\n\n // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined.\n const time = [hour, minute, second].join(timeDelimiter);\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${time}${tzOffset}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO9075 = formatISO9075;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO9075} function options.\n */\n\n/**\n * @name formatISO9075\n * @category Common Helpers\n * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).\n *\n * @description\n * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18 19:00:52'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075, short format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918 190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, date only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, time only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52'\n */\nfunction formatISO9075(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with a space\n const separator = result === \"\" ? \"\" : \" \";\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${hour}${timeDelimiter}${minute}${timeDelimiter}${second}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISODuration = formatISODuration;\n\n/**\n * @name formatISODuration\n * @category Common Helpers\n * @summary Format a duration object according as ISO 8601 duration string\n *\n * @description\n * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs//90001488-13/reference/r_iso_8601_duration_format.htm)\n *\n * @param duration - The duration to format\n *\n * @returns The ISO 8601 duration string\n *\n * @example\n * // Format the given duration as ISO 8601 string\n * const result = formatISODuration({\n * years: 39,\n * months: 2,\n * days: 20,\n * hours: 7,\n * minutes: 5,\n * seconds: 0\n * })\n * //=> 'P39Y2M20DT0H0M0S'\n */\nfunction formatISODuration(duration) {\n const {\n years = 0,\n months = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S`;\n}\n", "\"use strict\";\nexports.formatRFC3339 = formatRFC3339;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatRFC3339} function options.\n */\n\n/**\n * @name formatRFC3339\n * @category Common Helpers\n * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6).\n *\n * @description\n * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format:\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), {\n * fractionDigits: 3\n * })\n * //=> '2019-09-18T19:00:52.234Z'\n */\nfunction formatRFC3339(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const fractionDigits = options?.fractionDigits ?? 0;\n\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = date_.getFullYear();\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n let fractionalSecond = \"\";\n if (fractionDigits > 0) {\n const milliseconds = date_.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, fractionDigits - 3),\n );\n fractionalSecond =\n \".\" + (0, _index.addLeadingZeros)(fractionalSeconds, fractionDigits);\n }\n\n let offset = \"\";\n const tzOffset = date_.getTimezoneOffset();\n\n if (tzOffset !== 0) {\n const absoluteOffset = Math.abs(tzOffset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = tzOffset < 0 ? \"+\" : \"-\";\n\n offset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n offset = \"Z\";\n }\n\n return `${year}-${month}-${day}T${hour}:${minute}:${second}${fractionalSecond}${offset}`;\n}\n", "\"use strict\";\nexports.formatRFC7231 = formatRFC7231;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\nconst days = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\nconst months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\n/**\n * @name formatRFC7231\n * @category Common Helpers\n * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).\n *\n * @description\n * Return the formatted date string in RFC 7231 format.\n * The result will always be in UTC timezone.\n *\n * @param date - The original date\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 7231 format:\n * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))\n * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'\n */\nfunction formatRFC7231(date) {\n const _date = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(_date)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const dayName = days[_date.getUTCDay()];\n const dayOfMonth = (0, _index.addLeadingZeros)(_date.getUTCDate(), 2);\n const monthName = months[_date.getUTCMonth()];\n const year = _date.getUTCFullYear();\n\n const hour = (0, _index.addLeadingZeros)(_date.getUTCHours(), 2);\n const minute = (0, _index.addLeadingZeros)(_date.getUTCMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(_date.getUTCSeconds(), 2);\n\n // Result variables.\n return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;\n}\n", "\"use strict\";\nexports.formatRelative = formatRelative;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/normalizeDates.cjs\");\nvar _index4 = require(\"./differenceInCalendarDays.cjs\");\nvar _index5 = require(\"./format.cjs\");\n\n/**\n * The {@link formatRelative} function options.\n */\n\n/**\n * @name formatRelative\n * @category Common Helpers\n * @summary Represent the date in words relative to the given base date.\n *\n * @description\n * Represent the date in words relative to the given base date.\n *\n * | Distance to the base date | Result |\n * |---------------------------|---------------------------|\n * | Previous 6 days | last Sunday at 04:30 AM |\n * | Last day | yesterday at 04:30 AM |\n * | Same day | today at 04:30 AM |\n * | Next day | tomorrow at 04:30 AM |\n * | Next 6 days | Sunday at 04:30 AM |\n * | Other | 12/31/2017 |\n *\n * @param date - The date to format\n * @param baseDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The date in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws `options.locale` must contain `formatRelative` property\n *\n * @example\n * // Represent the date of 6 days ago in words relative to the given base date. In this example, today is Wednesday\n * const result = formatRelative(subDays(new Date(), 6), new Date())\n * //=> \"last Thursday at 12:45 AM\"\n */\nfunction formatRelative(date, baseDate, options) {\n const [date_, baseDate_] = (0, _index3.normalizeDates)(\n options?.in,\n date,\n baseDate,\n );\n\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const diff = (0, _index4.differenceInCalendarDays)(date_, baseDate_);\n\n if (isNaN(diff)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let token;\n if (diff < -6) {\n token = \"other\";\n } else if (diff < -1) {\n token = \"lastWeek\";\n } else if (diff < 0) {\n token = \"yesterday\";\n } else if (diff < 1) {\n token = \"today\";\n } else if (diff < 2) {\n token = \"tomorrow\";\n } else if (diff < 7) {\n token = \"nextWeek\";\n } else {\n token = \"other\";\n }\n\n const formatStr = locale.formatRelative(token, date_, baseDate_, {\n locale,\n weekStartsOn,\n });\n return (0, _index5.format)(date_, formatStr, { locale, weekStartsOn });\n}\n", "\"use strict\";\nexports.fromUnixTime = fromUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link fromUnixTime} function options.\n */\n\n/**\n * @name fromUnixTime\n * @category Timestamp Helpers\n * @summary Create a date from a Unix timestamp.\n *\n * @description\n * Create a date from a Unix timestamp (in seconds). Decimal values will be discarded.\n *\n * @param unixTime - The given Unix timestamp (in seconds)\n * @param options - An object with options. Allows to pass a context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @returns The date\n *\n * @example\n * // Create the date 29 February 2012 11:45:05:\n * const result = fromUnixTime(1330515905)\n * //=> Wed Feb 29 2012 11:45:05\n */\nfunction fromUnixTime(unixTime, options) {\n return (0, _index.toDate)(unixTime * 1000, options?.in);\n}\n", "\"use strict\";\nexports.getDate = getDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDate} function options.\n */\n\n/**\n * @name getDate\n * @category Day Helpers\n * @summary Get the day of the month of the given date.\n *\n * @description\n * Get the day of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The day of month\n *\n * @example\n * // Which day of the month is 29 February 2012?\n * const result = getDate(new Date(2012, 1, 29))\n * //=> 29\n */\nfunction getDate(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate();\n}\n", "\"use strict\";\nexports.getDay = getDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDay} function options.\n */\n\n/**\n * @name getDay\n * @category Weekday Helpers\n * @summary Get the day of the week of the given date.\n *\n * @description\n * Get the day of the week of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of week, 0 represents Sunday\n *\n * @example\n * // Which day of the week is 29 February 2012?\n * const result = getDay(new Date(2012, 1, 29))\n * //=> 3\n */\nfunction getDay(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay();\n}\n", "\"use strict\";\nexports.getDaysInMonth = getDaysInMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInMonth} function options.\n */\n\n/**\n * @name getDaysInMonth\n * @category Month Helpers\n * @summary Get the number of days in a month of the given date.\n *\n * @description\n * Get the number of days in a month of the given date, considering the context if provided.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a month\n *\n * @example\n * // How many days are in February 2000?\n * const result = getDaysInMonth(new Date(2000, 1))\n * //=> 29\n */\nfunction getDaysInMonth(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const monthIndex = _date.getMonth();\n const lastDayOfMonth = (0, _index.constructFrom)(_date, 0);\n lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);\n lastDayOfMonth.setHours(0, 0, 0, 0);\n return lastDayOfMonth.getDate();\n}\n", "\"use strict\";\nexports.isLeapYear = isLeapYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isLeapYear\n * @category Year Helpers\n * @summary Is the given date in the leap year?\n *\n * @description\n * Is the given date in the leap year?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is in the leap year\n *\n * @example\n * // Is 1 September 2012 in the leap year?\n * const result = isLeapYear(new Date(2012, 8, 1))\n * //=> true\n */\nfunction isLeapYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.getDaysInYear = getDaysInYear;\nvar _index = require(\"./isLeapYear.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInYear} function options.\n */\n\n/**\n * @name getDaysInYear\n * @category Year Helpers\n * @summary Get the number of days in a year of the given date.\n *\n * @description\n * Get the number of days in a year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a year\n *\n * @example\n * // How many days are in 2012?\n * const result = getDaysInYear(new Date(2012, 0, 1))\n * //=> 366\n */\nfunction getDaysInYear(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (Number.isNaN(+_date)) return NaN;\n return (0, _index.isLeapYear)(_date) ? 366 : 365;\n}\n", "\"use strict\";\nexports.getDecade = getDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDecade} function options.\n */\n\n/**\n * @name getDecade\n * @category Decade Helpers\n * @summary Get the decade of the given date.\n *\n * @description\n * Get the decade of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year of decade\n *\n * @example\n * // Which decade belongs 27 November 1942?\n * const result = getDecade(new Date(1942, 10, 27))\n * //=> 1940\n */\nfunction getDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n return decade;\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\n\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name getDefaultOptions\n * @category Common Helpers\n * @summary Get default options.\n * @pure false\n *\n * @description\n * Returns an object that contains defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * You can change these with [setDefaultOptions](https://date-fns.org/docs/setDefaultOptions).\n *\n * @returns The default options\n *\n * @example\n * const result = getDefaultOptions()\n * //=> {}\n *\n * @example\n * setDefaultOptions({ weekStarsOn: 1, firstWeekContainsDate: 4 })\n * const result = getDefaultOptions()\n * //=> { weekStarsOn: 1, firstWeekContainsDate: 4 }\n */\nfunction getDefaultOptions() {\n return Object.assign({}, (0, _index.getDefaultOptions)());\n}\n", "\"use strict\";\nexports.getHours = getHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getHours} function options.\n */\n\n/**\n * @name getHours\n * @category Hour Helpers\n * @summary Get the hours of the given date.\n *\n * @description\n * Get the hours of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The hours\n *\n * @example\n * // Get the hours of 29 February 2012 11:45:00:\n * const result = getHours(new Date(2012, 1, 29, 11, 45))\n * //=> 11\n */\nfunction getHours(date, options) {\n return (0, _index.toDate)(date, options?.in).getHours();\n}\n", "\"use strict\";\nexports.getISODay = getISODay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISODay} function options.\n */\n\n/**\n * @name getISODay\n * @category Weekday Helpers\n * @summary Get the day of the ISO week of the given date.\n *\n * @description\n * Get the day of the ISO week of the given date,\n * which is 7 for Sunday, 1 for Monday etc.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The day of ISO week\n *\n * @example\n * // Which day of the ISO week is 26 February 2012?\n * const result = getISODay(new Date(2012, 1, 26))\n * //=> 7\n */\nfunction getISODay(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 ? 7 : day;\n}\n", "\"use strict\";\nexports.getISOWeeksInYear = getISOWeeksInYear;\nvar _index = require(\"./addWeeks.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\n\n/**\n * The {@link getISOWeeksInYear} function options.\n */\n\n/**\n * @name getISOWeeksInYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * @description\n * Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of ISO weeks in a year\n *\n * @example\n * // How many weeks are in ISO week-numbering year 2015?\n * const result = getISOWeeksInYear(new Date(2015, 1, 11))\n * //=> 53\n */\nfunction getISOWeeksInYear(date, options) {\n const thisYear = (0, _index3.startOfISOWeekYear)(date, options);\n const nextYear = (0, _index3.startOfISOWeekYear)(\n (0, _index.addWeeks)(thisYear, 60),\n );\n const diff = +nextYear - +thisYear;\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index2.millisecondsInWeek);\n}\n", "\"use strict\";\nexports.getMilliseconds = getMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getMilliseconds\n * @category Millisecond Helpers\n * @summary Get the milliseconds of the given date.\n *\n * @description\n * Get the milliseconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The milliseconds\n *\n * @example\n * // Get the milliseconds of 29 February 2012 11:45:05.123:\n * const result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 123\n */\nfunction getMilliseconds(date) {\n return (0, _index.toDate)(date).getMilliseconds();\n}\n", "\"use strict\";\nexports.getMinutes = getMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMinutes} function options.\n */\n\n/**\n * @name getMinutes\n * @category Minute Helpers\n * @summary Get the minutes of the given date.\n *\n * @description\n * Get the minutes of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The minutes\n *\n * @example\n * // Get the minutes of 29 February 2012 11:45:05:\n * const result = getMinutes(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 45\n */\nfunction getMinutes(date, options) {\n return (0, _index.toDate)(date, options?.in).getMinutes();\n}\n", "\"use strict\";\nexports.getMonth = getMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMonth} function options.\n */\n\n/**\n * @name getMonth\n * @category Month Helpers\n * @summary Get the month of the given date.\n *\n * @description\n * Get the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The month index (0-11)\n *\n * @example\n * // Which month is 29 February 2012?\n * const result = getMonth(new Date(2012, 1, 29))\n * //=> 1\n */\nfunction getMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getMonth();\n}\n", "\"use strict\";\nexports.getOverlappingDaysInIntervals = getOverlappingDaysInIntervals;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name getOverlappingDaysInIntervals\n * @category Interval Helpers\n * @summary Get the number of days that overlap in two time intervals\n *\n * @description\n * Get the number of days that overlap in two time intervals. It uses the time\n * between dates to calculate the number of days, rounding it up to include\n * partial days.\n *\n * Two equal 0-length intervals will result in 0. Two equal 1ms intervals will\n * result in 1.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - An object with options\n *\n * @returns The number of days that overlap in two time intervals\n *\n * @example\n * // For overlapping time intervals adds 1 for each started overlapping day:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> 3\n *\n * @example\n * // For non-overlapping time intervals returns 0:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> 0\n */\n\nfunction getOverlappingDaysInIntervals(intervalLeft, intervalRight) {\n const [leftStart, leftEnd] = [\n +(0, _index3.toDate)(intervalLeft.start),\n +(0, _index3.toDate)(intervalLeft.end),\n ].sort((a, b) => a - b);\n const [rightStart, rightEnd] = [\n +(0, _index3.toDate)(intervalRight.start),\n +(0, _index3.toDate)(intervalRight.end),\n ].sort((a, b) => a - b);\n\n // Prevent NaN result if intervals don't overlap at all.\n const isOverlapping = leftStart < rightEnd && rightStart < leftEnd;\n if (!isOverlapping) return 0;\n\n // Remove the timezone offset to negate the DST effect on calculations.\n const overlapLeft = rightStart < leftStart ? leftStart : rightStart;\n const left =\n overlapLeft - (0, _index.getTimezoneOffsetInMilliseconds)(overlapLeft);\n const overlapRight = rightEnd > leftEnd ? leftEnd : rightEnd;\n const right =\n overlapRight - (0, _index.getTimezoneOffsetInMilliseconds)(overlapRight);\n\n // Ceil the number to include partial days too.\n return Math.ceil((right - left) / _index2.millisecondsInDay);\n}\n", "\"use strict\";\nexports.getSeconds = getSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getSeconds\n * @category Second Helpers\n * @summary Get the seconds of the given date.\n *\n * @description\n * Get the seconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The seconds\n *\n * @example\n * // Get the seconds of 29 February 2012 11:45:05.123:\n * const result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 5\n */\nfunction getSeconds(date) {\n return (0, _index.toDate)(date).getSeconds();\n}\n", "\"use strict\";\nexports.getTime = getTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getTime\n * @category Timestamp Helpers\n * @summary Get the milliseconds timestamp of the given date.\n *\n * @description\n * Get the milliseconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05.123:\n * const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 1330515905123\n */\nfunction getTime(date) {\n return +(0, _index.toDate)(date);\n}\n", "\"use strict\";\nexports.getUnixTime = getUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getUnixTime\n * @category Timestamp Helpers\n * @summary Get the seconds timestamp of the given date.\n *\n * @description\n * Get the seconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05 CET:\n * const result = getUnixTime(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 1330512305\n */\nfunction getUnixTime(date) {\n return Math.trunc(+(0, _index.toDate)(date) / 1000);\n}\n", "\"use strict\";\nexports.getWeekOfMonth = getWeekOfMonth;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./getDate.cjs\");\nvar _index3 = require(\"./getDay.cjs\");\nvar _index4 = require(\"./startOfMonth.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekOfMonth} function options.\n */\n\n/**\n * @name getWeekOfMonth\n * @category Week Helpers\n * @summary Get the week of the month of the given date.\n *\n * @description\n * Get the week of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The week of month\n *\n * @example\n * // Which week of the month is 9 November 2017?\n * const result = getWeekOfMonth(new Date(2017, 10, 9))\n * //=> 2\n */\nfunction getWeekOfMonth(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const currentDayOfMonth = (0, _index2.getDate)(\n (0, _index5.toDate)(date, options?.in),\n );\n if (isNaN(currentDayOfMonth)) return NaN;\n\n const startWeekDay = (0, _index3.getDay)(\n (0, _index4.startOfMonth)(date, options),\n );\n\n let lastDayOfFirstWeek = weekStartsOn - startWeekDay;\n if (lastDayOfFirstWeek <= 0) lastDayOfFirstWeek += 7;\n\n const remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek;\n return Math.ceil(remainingDaysAfterFirstWeek / 7) + 1;\n}\n", "\"use strict\";\nexports.lastDayOfMonth = lastDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfMonth} function options.\n */\n\n/**\n * @name lastDayOfMonth\n * @category Month Helpers\n * @summary Return the last day of a month for the given date.\n *\n * @description\n * Return the last day of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a month\n *\n * @example\n * // The last day of a month for 2 September 2014 11:55:00:\n * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.getWeeksInMonth = getWeeksInMonth;\nvar _index = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index2 = require(\"./lastDayOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeeksInMonth} function options.\n */\n\n/**\n * @name getWeeksInMonth\n * @category Week Helpers\n * @summary Get the number of calendar weeks a month spans.\n *\n * @description\n * Get the number of calendar weeks the month in the given date spans.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks does February 2015 span?\n * const result = getWeeksInMonth(new Date(2015, 1, 8))\n * //=> 4\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks does July 2017 span?\n * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })\n * //=> 6\n */\nfunction getWeeksInMonth(date, options) {\n const contextDate = (0, _index4.toDate)(date, options?.in);\n return (\n (0, _index.differenceInCalendarWeeks)(\n (0, _index2.lastDayOfMonth)(contextDate, options),\n (0, _index3.startOfMonth)(contextDate, options),\n options,\n ) + 1\n );\n}\n", "\"use strict\";\nexports.getYear = getYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getYear} function options.\n */\n\n/**\n * @name getYear\n * @category Year Helpers\n * @summary Get the year of the given date.\n *\n * @description\n * Get the year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year\n *\n * @example\n * // Which year is 2 July 2014?\n * const result = getYear(new Date(2014, 6, 2))\n * //=> 2014\n */\nfunction getYear(date, options) {\n return (0, _index.toDate)(date, options?.in).getFullYear();\n}\n", "\"use strict\";\nexports.hoursToMilliseconds = hoursToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMilliseconds\n * @category Conversion Helpers\n * @summary Convert hours to milliseconds.\n *\n * @description\n * Convert a number of hours to a full number of milliseconds.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted to milliseconds\n *\n * @example\n * // Convert 2 hours to milliseconds:\n * const result = hoursToMilliseconds(2)\n * //=> 7200000\n */\nfunction hoursToMilliseconds(hours) {\n return Math.trunc(hours * _index.millisecondsInHour);\n}\n", "\"use strict\";\nexports.hoursToMinutes = hoursToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMinutes\n * @category Conversion Helpers\n * @summary Convert hours to minutes.\n *\n * @description\n * Convert a number of hours to a full number of minutes.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted in minutes\n *\n * @example\n * // Convert 2 hours to minutes:\n * const result = hoursToMinutes(2)\n * //=> 120\n */\nfunction hoursToMinutes(hours) {\n return Math.trunc(hours * _index.minutesInHour);\n}\n", "\"use strict\";\nexports.hoursToSeconds = hoursToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToSeconds\n * @category Conversion Helpers\n * @summary Convert hours to seconds.\n *\n * @description\n * Convert a number of hours to a full number of seconds.\n *\n * @param hours - The number of hours to be converted\n *\n * @returns The number of hours converted in seconds\n *\n * @example\n * // Convert 2 hours to seconds:\n * const result = hoursToSeconds(2)\n * //=> 7200\n */\nfunction hoursToSeconds(hours) {\n return Math.trunc(hours * _index.secondsInHour);\n}\n", "\"use strict\";\nexports.interval = interval;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link interval} function options.\n */\n\n/**\n * The {@link interval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the start argument,\n * then the end interval date. If a context function is passed, it uses the context\n * function return type.\n */\n\n/**\n * @name interval\n * @category Interval Helpers\n * @summary Creates an interval object and validates its values.\n *\n * @description\n * Creates a normalized interval object and validates its values. If the interval is invalid, an exception is thrown.\n *\n * @typeParam StartDate - Start date type.\n * @typeParam EndDate - End date type.\n * @typeParam Options - Options type.\n *\n * @param start - The start of the interval.\n * @param end - The end of the interval.\n * @param options - The options object.\n *\n * @throws `Start date is invalid` when `start` is invalid.\n * @throws `End date is invalid` when `end` is invalid.\n * @throws `End date must be after start date` when end is before `start` and `options.assertPositive` is true.\n *\n * @returns The normalized and validated interval object.\n */\nfunction interval(start, end, options) {\n const [_start, _end] = (0, _index.normalizeDates)(options?.in, start, end);\n\n if (isNaN(+_start)) throw new TypeError(\"Start date is invalid\");\n if (isNaN(+_end)) throw new TypeError(\"End date is invalid\");\n\n if (options?.assertPositive && +_start > +_end)\n throw new TypeError(\"End date must be after start date\");\n\n return { start: _start, end: _end };\n}\n", "\"use strict\";\nexports.intervalToDuration = intervalToDuration;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./add.cjs\");\nvar _index3 = require(\"./differenceInDays.cjs\");\nvar _index4 = require(\"./differenceInHours.cjs\");\nvar _index5 = require(\"./differenceInMinutes.cjs\");\nvar _index6 = require(\"./differenceInMonths.cjs\");\nvar _index7 = require(\"./differenceInSeconds.cjs\");\nvar _index8 = require(\"./differenceInYears.cjs\");\n\n/**\n * The {@link intervalToDuration} function options.\n */\n\n/**\n * @name intervalToDuration\n * @category Common Helpers\n * @summary Convert interval to duration\n *\n * @description\n * Convert an interval object to a duration object.\n *\n * @param interval - The interval to convert to duration\n * @param options - The context options\n *\n * @returns The duration object\n *\n * @example\n * // Get the duration between January 15, 1929 and April 4, 1968.\n * intervalToDuration({\n * start: new Date(1929, 0, 15, 12, 0, 0),\n * end: new Date(1968, 3, 4, 19, 5, 0)\n * });\n * //=> { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }\n */\nfunction intervalToDuration(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const duration = {};\n\n const years = (0, _index8.differenceInYears)(end, start);\n if (years) duration.years = years;\n\n const remainingMonths = (0, _index2.add)(start, { years: duration.years });\n const months = (0, _index6.differenceInMonths)(end, remainingMonths);\n if (months) duration.months = months;\n\n const remainingDays = (0, _index2.add)(remainingMonths, {\n months: duration.months,\n });\n const days = (0, _index3.differenceInDays)(end, remainingDays);\n if (days) duration.days = days;\n\n const remainingHours = (0, _index2.add)(remainingDays, {\n days: duration.days,\n });\n const hours = (0, _index4.differenceInHours)(end, remainingHours);\n if (hours) duration.hours = hours;\n\n const remainingMinutes = (0, _index2.add)(remainingHours, {\n hours: duration.hours,\n });\n const minutes = (0, _index5.differenceInMinutes)(end, remainingMinutes);\n if (minutes) duration.minutes = minutes;\n\n const remainingSeconds = (0, _index2.add)(remainingMinutes, {\n minutes: duration.minutes,\n });\n const seconds = (0, _index7.differenceInSeconds)(end, remainingSeconds);\n if (seconds) duration.seconds = seconds;\n\n return duration;\n}\n", "\"use strict\";\nexports.intlFormat = intlFormat;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The locale string (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).\n * @deprecated\n *\n * [TODO] Remove in v4\n */\n\n/**\n * The format options (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options)\n */\n\n/**\n * The locale options.\n */\n\n/**\n * @name intlFormat\n * @category Common Helpers\n * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).\n *\n * @description\n * Return the formatted date string in the given format.\n * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside.\n * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options)\n *\n * > \u26A0\uFE0F Please note that before Node version 13.0.0, only the locale data for en-US is available by default.\n *\n * @param date - The date to format\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in middle-endian format:\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456))\n * //=> 10/4/2019\n */\n\n/**\n * @param date - The date to format\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in Korean.\n * // Convert the date with locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * locale: 'ko-KR',\n * })\n * //=> 2019. 10. 4.\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019.\n * // Convert the date with format's options.\n * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * year: 'numeric',\n * month: 'numeric',\n * day: 'numeric',\n * hour: 'numeric',\n * })\n * //=> 10/4/2019, 12 PM\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in German.\n * // Convert the date with format's options and locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * weekday: 'long',\n * year: 'numeric',\n * month: 'long',\n * day: 'numeric',\n * }, {\n * locale: 'de-DE',\n * })\n * //=> Freitag, 4. Oktober 2019\n */\n\nfunction intlFormat(date, formatOrLocale, localeOptions) {\n let formatOptions;\n\n if (isFormatOptions(formatOrLocale)) {\n formatOptions = formatOrLocale;\n } else {\n localeOptions = formatOrLocale;\n }\n\n return new Intl.DateTimeFormat(localeOptions?.locale, formatOptions).format(\n (0, _index.toDate)(date),\n );\n}\n\nfunction isFormatOptions(opts) {\n return opts !== undefined && !(\"locale\" in opts);\n}\n", "\"use strict\";\nexports.intlFormatDistance = intlFormatDistance;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index5 = require(\"./differenceInCalendarQuarters.cjs\");\nvar _index6 = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index7 = require(\"./differenceInCalendarYears.cjs\");\nvar _index8 = require(\"./differenceInHours.cjs\");\nvar _index9 = require(\"./differenceInMinutes.cjs\");\nvar _index10 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link intlFormatDistance} function options.\n */\n\n/**\n * The unit used to format the distance in {@link intlFormatDistance}.\n */\n\n/**\n * @name intlFormatDistance\n * @category Common Helpers\n * @summary Formats distance between two dates in a human-readable format\n * @description\n * The function calculates the difference between two dates and formats it as a human-readable string.\n *\n * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`.\n *\n * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`.\n *\n * See the table below for the unit picking logic:\n *\n * | Distance between dates | Result (past) | Result (future) |\n * | ---------------------- | -------------- | --------------- |\n * | 0 seconds | now | now |\n * | 1-59 seconds | X seconds ago | in X seconds |\n * | 1-59 minutes | X minutes ago | in X minutes |\n * | 1-23 hours | X hours ago | in X hours |\n * | 1 day | yesterday | tomorrow |\n * | 2-6 days | X days ago | in X days |\n * | 7 days | last week | next week |\n * | 8 days-1 month | X weeks ago | in X weeks |\n * | 1 month | last month | next month |\n * | 2-3 months | X months ago | in X months |\n * | 1 quarter | last quarter | next quarter |\n * | 2-3 quarters | X quarters ago | in X quarters |\n * | 1 year | last year | next year |\n * | 2+ years | X years ago | in X years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with.\n * @param options - An object with options.\n * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)\n * The narrow one could be similar to the short one for some locales.\n *\n * @returns The distance in words according to language-sensitive relative time formatting.\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must not be invalid Unit\n * @throws `options.locale` must not be invalid locale\n * @throws `options.localeMatcher` must not be invalid localeMatcher\n * @throws `options.numeric` must not be invalid numeric\n * @throws `options.style` must not be invalid style\n *\n * @example\n * // What is the distance between the dates when the fist date is after the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0)\n * )\n * //=> 'in 1 hour'\n *\n * // What is the distance between the dates when the fist date is before the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0)\n * )\n * //=> '1 hour ago'\n *\n * @example\n * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return \"next year\"\n * intlFormatDistance(\n * new Date(1987, 6, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { unit: 'quarter' }\n * )\n * //=> 'in 5 quarters'\n *\n * @example\n * // Use the locale option to get the result in Spanish. Without setting it, the example would return \"in 1 hour\".\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { locale: 'es' }\n * )\n * //=> 'dentro de 1 hora'\n *\n * @example\n * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return \"tomorrow\".\n * intlFormatDistance(\n * new Date(1986, 3, 5, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { numeric: 'always' }\n * )\n * //=> 'in 1 day'\n *\n * @example\n * // Use the style option to force the function to use short values. Without setting it, the example would return \"in 2 years\".\n * intlFormatDistance(\n * new Date(1988, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { style: 'short' }\n * )\n * //=> 'in 2 yr'\n */\nfunction intlFormatDistance(laterDate, earlierDate, options) {\n let value = 0;\n let unit;\n\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!options?.unit) {\n // Get the unit based on diffInSeconds calculations if no unit is specified\n const diffInSeconds = (0, _index10.differenceInSeconds)(\n laterDate_,\n earlierDate_,\n ); // The smallest unit\n\n if (Math.abs(diffInSeconds) < _index2.secondsInMinute) {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n unit = \"second\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInHour) {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n unit = \"minute\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInDay &&\n Math.abs(\n (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_),\n ) < 1\n ) {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n unit = \"hour\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInWeek &&\n (value = (0, _index3.differenceInCalendarDays)(\n laterDate_,\n earlierDate_,\n )) &&\n Math.abs(value) < 7\n ) {\n unit = \"day\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInMonth) {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n unit = \"week\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInQuarter) {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n unit = \"month\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInYear) {\n if (\n (0, _index5.differenceInCalendarQuarters)(laterDate_, earlierDate_) < 4\n ) {\n // To filter out cases that are less than a year but match 4 quarters\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n unit = \"quarter\";\n } else {\n value = (0, _index7.differenceInCalendarYears)(\n laterDate_,\n earlierDate_,\n );\n unit = \"year\";\n }\n } else {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n unit = \"year\";\n }\n } else {\n // Get the value if unit is specified\n unit = options?.unit;\n if (unit === \"second\") {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n } else if (unit === \"minute\") {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n } else if (unit === \"hour\") {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n } else if (unit === \"day\") {\n value = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n } else if (unit === \"week\") {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n } else if (unit === \"month\") {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n } else if (unit === \"quarter\") {\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n } else if (unit === \"year\") {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n }\n }\n\n const rtf = new Intl.RelativeTimeFormat(options?.locale, {\n numeric: \"auto\",\n ...options,\n });\n\n return rtf.format(value, unit);\n}\n", "\"use strict\";\nexports.isAfter = isAfter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isAfter\n * @category Common Helpers\n * @summary Is the first date after the second one?\n *\n * @description\n * Is the first date after the second one?\n *\n * @param date - The date that should be after the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is after the second date\n *\n * @example\n * // Is 10 July 1989 after 11 February 1987?\n * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> true\n */\nfunction isAfter(date, dateToCompare) {\n return +(0, _index.toDate)(date) > +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isBefore = isBefore;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isBefore\n * @category Common Helpers\n * @summary Is the first date before the second one?\n *\n * @description\n * Is the first date before the second one?\n *\n * @param date - The date that should be before the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is before the second date\n *\n * @example\n * // Is 10 July 1989 before 11 February 1987?\n * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> false\n */\nfunction isBefore(date, dateToCompare) {\n return +(0, _index.toDate)(date) < +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isEqual = isEqual;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isEqual\n * @category Common Helpers\n * @summary Are the given dates equal?\n *\n * @description\n * Are the given dates equal?\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The dates are equal\n *\n * @example\n * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?\n * const result = isEqual(\n * new Date(2014, 6, 2, 6, 30, 45, 0),\n * new Date(2014, 6, 2, 6, 30, 45, 500)\n * )\n * //=> false\n */\nfunction isEqual(leftDate, rightDate) {\n return +(0, _index.toDate)(leftDate) === +(0, _index.toDate)(rightDate);\n}\n", "\"use strict\";\nexports.isExists = isExists; /**\n * @name isExists\n * @category Common Helpers\n * @summary Is the given date exists?\n *\n * @description\n * Checks if the given arguments convert to an existing date.\n *\n * @param year - The year of the date to check\n * @param month - The month of the date to check\n * @param day - The day of the date to check\n *\n * @returns `true` if the date exists\n *\n * @example\n * // For the valid date:\n * const result = isExists(2018, 0, 31)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isExists(2018, 1, 31)\n * //=> false\n */\nfunction isExists(year, month, day) {\n const date = new Date(year, month, day);\n return (\n date.getFullYear() === year &&\n date.getMonth() === month &&\n date.getDate() === day\n );\n}\n", "\"use strict\";\nexports.isFirstDayOfMonth = isFirstDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFirstDayOfMonth} function options.\n */\n\n/**\n * @name isFirstDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the first day of a month?\n *\n * @description\n * Is the given date the first day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the first day of a month\n *\n * @example\n * // Is 1 September 2014 the first day of a month?\n * const result = isFirstDayOfMonth(new Date(2014, 8, 1))\n * //=> true\n */\nfunction isFirstDayOfMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate() === 1;\n}\n", "\"use strict\";\nexports.isFriday = isFriday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFriday} function options.\n */\n\n/**\n * @name isFriday\n * @category Weekday Helpers\n * @summary Is the given date Friday?\n *\n * @description\n * Is the given date Friday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Friday\n *\n * @example\n * // Is 26 September 2014 Friday?\n * const result = isFriday(new Date(2014, 8, 26))\n * //=> true\n */\nfunction isFriday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 5;\n}\n", "\"use strict\";\nexports.isFuture = isFuture;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isFuture\n * @category Common Helpers\n * @summary Is the given date in the future?\n * @pure false\n *\n * @description\n * Is the given date in the future?\n *\n * @param date - The date to check\n *\n * @returns The date is in the future\n *\n * @example\n * // If today is 6 October 2014, is 31 December 2014 in the future?\n * const result = isFuture(new Date(2014, 11, 31))\n * //=> true\n */\nfunction isFuture(date) {\n return +(0, _index.toDate)(date) > Date.now();\n}\n", "\"use strict\";\nexports.transpose = transpose;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name transpose\n * @category Generic Helpers\n * @summary Transpose the date to the given constructor.\n *\n * @description\n * The function transposes the date to the given constructor. It helps you\n * to transpose the date in the system time zone to say `UTCDate` or any other\n * date extension.\n *\n * @typeParam InputDate - The input `Date` type derived from the passed argument.\n * @typeParam ResultDate - The result `Date` type derived from the passed constructor.\n *\n * @param date - The date to use values from\n * @param constructor - The date constructor to use\n *\n * @returns Date transposed to the given constructor\n *\n * @example\n * // Create July 10, 2022 00:00 in locale time zone\n * const date = new Date(2022, 6, 10)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'\n *\n * @example\n * // Transpose the date to July 10, 2022 00:00 in UTC\n * transpose(date, UTCDate)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'\n */\nfunction transpose(date, constructor) {\n const date_ = isConstructor(constructor)\n ? new constructor(0)\n : (0, _index.constructFrom)(constructor, 0);\n date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());\n date_.setHours(\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n date.getMilliseconds(),\n );\n return date_;\n}\n\nfunction isConstructor(constructor) {\n return (\n typeof constructor === \"function\" &&\n constructor.prototype?.constructor === constructor\n );\n}\n", "\"use strict\";\nexports.ValueSetter = exports.Setter = exports.DateTimezoneSetter = void 0;\nvar _index = require(\"../../constructFrom.cjs\");\nvar _index2 = require(\"../../transpose.cjs\");\n\nconst TIMEZONE_UNIT_PRIORITY = 10;\n\nclass Setter {\n subPriority = 0;\n\n validate(_utcDate, _options) {\n return true;\n }\n}\nexports.Setter = Setter;\n\nclass ValueSetter extends Setter {\n constructor(\n value,\n\n validateValue,\n\n setValue,\n\n priority,\n subPriority,\n ) {\n super();\n this.value = value;\n this.validateValue = validateValue;\n this.setValue = setValue;\n this.priority = priority;\n if (subPriority) {\n this.subPriority = subPriority;\n }\n }\n\n validate(date, options) {\n return this.validateValue(date, this.value, options);\n }\n\n set(date, flags, options) {\n return this.setValue(date, flags, this.value, options);\n }\n}\nexports.ValueSetter = ValueSetter;\n\nclass DateTimezoneSetter extends Setter {\n priority = TIMEZONE_UNIT_PRIORITY;\n subPriority = -1;\n\n constructor(context, reference) {\n super();\n this.context =\n context || ((date) => (0, _index.constructFrom)(reference, date));\n }\n\n set(date, flags) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n (0, _index2.transpose)(date, this.context),\n );\n }\n}\nexports.DateTimezoneSetter = DateTimezoneSetter;\n", "\"use strict\";\nexports.Parser = void 0;\nvar _Setter = require(\"./Setter.cjs\");\n\nclass Parser {\n run(dateString, token, match, options) {\n const result = this.parse(dateString, token, match, options);\n if (!result) {\n return null;\n }\n\n return {\n setter: new _Setter.ValueSetter(\n result.value,\n this.validate,\n this.set,\n this.priority,\n this.subPriority,\n ),\n rest: result.rest,\n };\n }\n\n validate(_utcDate, _value, _options) {\n return true;\n }\n}\nexports.Parser = Parser;\n", "\"use strict\";\nexports.EraParser = void 0;\n\nvar _Parser = require(\"../Parser.cjs\");\n\nclass EraParser extends _Parser.Parser {\n priority = 140;\n\n parse(dateString, token, match) {\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return (\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n\n // A, B\n case \"GGGGG\":\n return match.era(dateString, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return (\n match.era(dateString, { width: \"wide\" }) ||\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n }\n }\n\n set(date, flags, value) {\n flags.era = value;\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"R\", \"u\", \"t\", \"T\"];\n}\nexports.EraParser = EraParser;\n", "\"use strict\";\nexports.timezonePatterns = exports.numericPatterns = void 0;\nconst numericPatterns = (exports.numericPatterns = {\n month: /^(1[0-2]|0?\\d)/, // 0 to 12\n date: /^(3[0-1]|[0-2]?\\d)/, // 0 to 31\n dayOfYear: /^(36[0-6]|3[0-5]\\d|[0-2]?\\d?\\d)/, // 0 to 366\n week: /^(5[0-3]|[0-4]?\\d)/, // 0 to 53\n hour23h: /^(2[0-3]|[0-1]?\\d)/, // 0 to 23\n hour24h: /^(2[0-4]|[0-1]?\\d)/, // 0 to 24\n hour11h: /^(1[0-1]|0?\\d)/, // 0 to 11\n hour12h: /^(1[0-2]|0?\\d)/, // 0 to 12\n minute: /^[0-5]?\\d/, // 0 to 59\n second: /^[0-5]?\\d/, // 0 to 59\n\n singleDigit: /^\\d/, // 0 to 9\n twoDigits: /^\\d{1,2}/, // 0 to 99\n threeDigits: /^\\d{1,3}/, // 0 to 999\n fourDigits: /^\\d{1,4}/, // 0 to 9999\n\n anyDigitsSigned: /^-?\\d+/,\n singleDigitSigned: /^-?\\d/, // 0 to 9, -0 to -9\n twoDigitsSigned: /^-?\\d{1,2}/, // 0 to 99, -0 to -99\n threeDigitsSigned: /^-?\\d{1,3}/, // 0 to 999, -0 to -999\n fourDigitsSigned: /^-?\\d{1,4}/, // 0 to 9999, -0 to -9999\n});\n\nconst timezonePatterns = (exports.timezonePatterns = {\n basicOptionalMinutes: /^([+-])(\\d{2})(\\d{2})?|Z/,\n basic: /^([+-])(\\d{2})(\\d{2})|Z/,\n basicOptionalSeconds: /^([+-])(\\d{2})(\\d{2})((\\d{2}))?|Z/,\n extended: /^([+-])(\\d{2}):(\\d{2})|Z/,\n extendedOptionalSeconds: /^([+-])(\\d{2}):(\\d{2})(:(\\d{2}))?|Z/,\n});\n", "\"use strict\";\nexports.dayPeriodEnumToHours = dayPeriodEnumToHours;\nexports.isLeapYearIndex = isLeapYearIndex;\nexports.mapValue = mapValue;\nexports.normalizeTwoDigitYear = normalizeTwoDigitYear;\nexports.parseAnyDigitsSigned = parseAnyDigitsSigned;\nexports.parseNDigits = parseNDigits;\nexports.parseNDigitsSigned = parseNDigitsSigned;\nexports.parseNumericPattern = parseNumericPattern;\nexports.parseTimezonePattern = parseTimezonePattern;\nvar _index = require(\"../../constants.cjs\");\n\nvar _constants = require(\"./constants.cjs\");\n\nfunction mapValue(parseFnResult, mapFn) {\n if (!parseFnResult) {\n return parseFnResult;\n }\n\n return {\n value: mapFn(parseFnResult.value),\n rest: parseFnResult.rest,\n };\n}\n\nfunction parseNumericPattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n return {\n value: parseInt(matchResult[0], 10),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseTimezonePattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n // Input is 'Z'\n if (matchResult[0] === \"Z\") {\n return {\n value: 0,\n rest: dateString.slice(1),\n };\n }\n\n const sign = matchResult[1] === \"+\" ? 1 : -1;\n const hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;\n const minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;\n const seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;\n\n return {\n value:\n sign *\n (hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * _index.millisecondsInSecond),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseAnyDigitsSigned(dateString) {\n return parseNumericPattern(\n _constants.numericPatterns.anyDigitsSigned,\n dateString,\n );\n}\n\nfunction parseNDigits(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigit,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigits,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigits,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigits,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction parseNDigitsSigned(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigitSigned,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigitsSigned,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigitsSigned,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigitsSigned,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^-?\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction dayPeriodEnumToHours(dayPeriod) {\n switch (dayPeriod) {\n case \"morning\":\n return 4;\n case \"evening\":\n return 17;\n case \"pm\":\n case \"noon\":\n case \"afternoon\":\n return 12;\n case \"am\":\n case \"midnight\":\n case \"night\":\n default:\n return 0;\n }\n}\n\nfunction normalizeTwoDigitYear(twoDigitYear, currentYear) {\n const isCommonEra = currentYear > 0;\n // Absolute number of the current year:\n // 1 -> 1 AC\n // 0 -> 1 BC\n // -1 -> 2 BC\n const absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;\n\n let result;\n if (absCurrentYear <= 50) {\n result = twoDigitYear || 100;\n } else {\n const rangeEnd = absCurrentYear + 50;\n const rangeEndCentury = Math.trunc(rangeEnd / 100) * 100;\n const isPreviousCentury = twoDigitYear >= rangeEnd % 100;\n result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);\n }\n\n return isCommonEra ? result : 1 - result;\n}\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.YearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns\n// | Year | y | yy | yyy | yyyy | yyyyy |\n// |----------|-------|----|-------|-------|-------|\n// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\nclass YearParser extends _Parser.Parser {\n priority = 130;\n incompatibleTokens = [\"Y\", \"R\", \"u\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"yy\",\n });\n\n switch (token) {\n case \"y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value) {\n const currentYear = date.getFullYear();\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(normalizedTwoDigitYear, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.YearParser = YearParser;\n", "\"use strict\";\nexports.LocalWeekYearParser = void 0;\nvar _index = require(\"../../../getWeekYear.cjs\");\n\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week-numbering year\nclass LocalWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"YY\",\n });\n\n switch (token) {\n case \"Y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"Yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value, options) {\n const currentYear = (0, _index.getWeekYear)(date, options);\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(\n normalizedTwoDigitYear,\n 0,\n options.firstWeekContainsDate,\n );\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, options.firstWeekContainsDate);\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekYearParser = LocalWeekYearParser;\n", "\"use strict\";\nexports.ISOWeekYearParser = void 0;\nvar _index = require(\"../../../startOfISOWeek.cjs\");\nvar _index2 = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week-numbering year\nclass ISOWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"R\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n const firstWeekOfYear = (0, _index2.constructFrom)(date, 0);\n firstWeekOfYear.setFullYear(value, 0, 4);\n firstWeekOfYear.setHours(0, 0, 0, 0);\n return (0, _index.startOfISOWeek)(firstWeekOfYear);\n }\n\n incompatibleTokens = [\n \"G\",\n \"y\",\n \"Y\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekYearParser = ISOWeekYearParser;\n", "\"use strict\";\nexports.ExtendedYearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass ExtendedYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"u\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"G\", \"y\", \"Y\", \"R\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.ExtendedYearParser = ExtendedYearParser;\n", "\"use strict\";\nexports.QuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass QuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n case \"QQ\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.QuarterParser = QuarterParser;\n", "\"use strict\";\nexports.StandAloneQuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneQuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n case \"qq\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneQuarterParser = StandAloneQuarterParser;\n", "\"use strict\";\nexports.MonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MonthParser extends _Parser.Parser {\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"L\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"M\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"MM\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // J, F, ..., D\n case \"MMMMM\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.MonthParser = MonthParser;\n", "\"use strict\";\nexports.StandAloneMonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneMonthParser extends _Parser.Parser {\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // J, F, ..., D\n case \"LLLLL\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneMonthParser = StandAloneMonthParser;\n", "\"use strict\";\nexports.setWeek = setWeek;\nvar _index = require(\"./getWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeek} function options.\n */\n\n/**\n * @name setWeek\n * @category Week Helpers\n * @summary Set the local week to the given date.\n *\n * @description\n * Set the local week to the given date, saving the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param week - The week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week set\n *\n * @example\n * // Set the 1st week to 2 January 2005 with default options:\n * const result = setWeek(new Date(2005, 0, 2), 1)\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // Set the 1st week to 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January:\n * const result = setWeek(new Date(2005, 0, 2), 1, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sun Jan 4 2004 00:00:00\n */\nfunction setWeek(date, week, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getWeek)(date_, options) - week;\n date_.setDate(date_.getDate() - diff * 7);\n return (0, _index2.toDate)(date_, options?.in);\n}\n", "\"use strict\";\nexports.LocalWeekParser = void 0;\nvar _index = require(\"../../../setWeek.cjs\");\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week of year\nclass LocalWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"w\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"wo\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value, options) {\n return (0, _index2.startOfWeek)(\n (0, _index.setWeek)(date, value, options),\n options,\n );\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekParser = LocalWeekParser;\n", "\"use strict\";\nexports.setISOWeek = setISOWeek;\nvar _index = require(\"./getISOWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeek} function options.\n */\n\n/**\n * @name setISOWeek\n * @category ISO Week Helpers\n * @summary Set the ISO week to the given date.\n *\n * @description\n * Set the ISO week to the given date, saving the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The `Date` type of the context function.\n *\n * @param date - The date to be changed\n * @param week - The ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week set\n *\n * @example\n * // Set the 53rd ISO week to 7 August 2004:\n * const result = setISOWeek(new Date(2004, 7, 7), 53)\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setISOWeek(date, week, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getISOWeek)(_date, options) - week;\n _date.setDate(_date.getDate() - diff * 7);\n return _date;\n}\n", "\"use strict\";\nexports.ISOWeekParser = void 0;\nvar _index = require(\"../../../setISOWeek.cjs\");\nvar _index2 = require(\"../../../startOfISOWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week of year\nclass ISOWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"I\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"Io\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value) {\n return (0, _index2.startOfISOWeek)((0, _index.setISOWeek)(date, value));\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekParser = ISOWeekParser;\n", "\"use strict\";\nexports.DateParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst DAYS_IN_MONTH_LEAP_YEAR = [\n 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n];\n\n// Day of the month\nclass DateParser extends _Parser.Parser {\n priority = 90;\n subPriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"d\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.date,\n dateString,\n );\n case \"do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n const month = date.getMonth();\n if (isLeapYear) {\n return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];\n } else {\n return value >= 1 && value <= DAYS_IN_MONTH[month];\n }\n }\n\n set(date, _flags, value) {\n date.setDate(value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DateParser = DateParser;\n", "\"use strict\";\nexports.DayOfYearParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass DayOfYearParser extends _Parser.Parser {\n priority = 90;\n\n subpriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"D\":\n case \"DD\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.dayOfYear,\n dateString,\n );\n case \"Do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n if (isLeapYear) {\n return value >= 1 && value <= 366;\n } else {\n return value >= 1 && value <= 365;\n }\n }\n\n set(date, _flags, value) {\n date.setMonth(0, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"E\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DayOfYearParser = DayOfYearParser;\n", "\"use strict\";\nexports.setDay = setDay;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDay} function options.\n */\n\n/**\n * @name setDay\n * @category Weekday Helpers\n * @summary Set the day of the week to the given date.\n *\n * @description\n * Set the day of the week to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the week of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the day of the week set\n *\n * @example\n * // Set week day to Sunday, with the default weekStartsOn of Sunday:\n * const result = setDay(new Date(2014, 8, 1), 0)\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Set week day to Sunday, with a weekStartsOn of Monday:\n * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setDay(date, day, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = date_.getDay();\n\n const remainder = day % 7;\n const dayIndex = (remainder + 7) % 7;\n\n const delta = 7 - weekStartsOn;\n const diff =\n day < 0 || day > 6\n ? day - ((currentDay + delta) % 7)\n : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);\n return (0, _index2.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.DayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\n// Day of week\nclass DayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"EEEEE\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"EEEE\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"D\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.DayParser = DayParser;\n", "\"use strict\";\nexports.LocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local day of week\nclass LocalDayParser extends _Parser.Parser {\n priority = 90;\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"e\":\n case \"ee\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"eo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"eee\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"eeeee\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"eeee\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalDayParser = LocalDayParser;\n", "\"use strict\";\nexports.StandAloneLocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Stand-alone local day of week\nclass StandAloneLocalDayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"c\":\n case \"cc\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"co\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"ccc\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // T\n case \"ccccc\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return (\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // Tuesday\n case \"cccc\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"e\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneLocalDayParser = StandAloneLocalDayParser;\n", "\"use strict\";\nexports.setISODay = setISODay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getISODay.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISODay} function options.\n */\n\n/**\n * @name setISODay\n * @category Weekday Helpers\n * @summary Set the day of the ISO week to the given date.\n *\n * @description\n * Set the day of the ISO week to the given date.\n * ISO week starts with Monday.\n * 7 is the index of Sunday, 1 is the index of Monday, etc.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the ISO week set\n *\n * @example\n * // Set Sunday to 1 September 2014:\n * const result = setISODay(new Date(2014, 8, 1), 7)\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setISODay(date, day, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = (0, _index2.getISODay)(date_, options);\n const diff = day - currentDay;\n return (0, _index.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.ISODayParser = void 0;\nvar _index = require(\"../../../setISODay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO day of week\nclass ISODayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => {\n if (value === 0) {\n return 7;\n }\n return value;\n };\n\n switch (token) {\n // 2\n case \"i\":\n case \"ii\": // 02\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 2nd\n case \"io\":\n return match.ordinalNumber(dateString, { unit: \"day\" });\n // Tue\n case \"iii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // T\n case \"iiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tu\n case \"iiiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tuesday\n case \"iiii\":\n default:\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 7;\n }\n\n set(date, _flags, value) {\n date = (0, _index.setISODay)(date, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"E\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISODayParser = ISODayParser;\n", "\"use strict\";\nexports.AMPMParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"a\":\n case \"aa\":\n case \"aaa\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"aaaaa\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"b\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMParser = AMPMParser;\n", "\"use strict\";\nexports.AMPMMidnightParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMMidnightParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"b\":\n case \"bb\":\n case \"bbb\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"bbbbb\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMMidnightParser = AMPMMidnightParser;\n", "\"use strict\";\nexports.DayPeriodParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// in the morning, in the afternoon, in the evening, at night\nclass DayPeriodParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"BBBBB\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"t\", \"T\"];\n}\nexports.DayPeriodParser = DayPeriodParser;\n", "\"use strict\";\nexports.Hour1to12Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1to12Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"h\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour12h,\n dateString,\n );\n case \"ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 12;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else if (!isPM && value === 12) {\n date.setHours(0, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"H\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour1to12Parser = Hour1to12Parser;\n", "\"use strict\";\nexports.Hour0to23Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0to23Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"H\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour23h,\n dateString,\n );\n case \"Ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 23;\n }\n\n set(date, _flags, value) {\n date.setHours(value, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0to23Parser = Hour0to23Parser;\n", "\"use strict\";\nexports.Hour0To11Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0To11Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"K\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour11h,\n dateString,\n );\n case \"Ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"h\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0To11Parser = Hour0To11Parser;\n", "\"use strict\";\nexports.Hour1To24Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1To24Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"k\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour24h,\n dateString,\n );\n case \"ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 24;\n }\n\n set(date, _flags, value) {\n const hours = value <= 24 ? value % 24 : value;\n date.setHours(hours, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"H\", \"K\", \"t\", \"T\"];\n}\nexports.Hour1To24Parser = Hour1To24Parser;\n", "\"use strict\";\nexports.MinuteParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MinuteParser extends _Parser.Parser {\n priority = 60;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"m\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.minute,\n dateString,\n );\n case \"mo\":\n return match.ordinalNumber(dateString, { unit: \"minute\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setMinutes(value, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.MinuteParser = MinuteParser;\n", "\"use strict\";\nexports.SecondParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass SecondParser extends _Parser.Parser {\n priority = 50;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"s\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.second,\n dateString,\n );\n case \"so\":\n return match.ordinalNumber(dateString, { unit: \"second\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setSeconds(value, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.SecondParser = SecondParser;\n", "\"use strict\";\nexports.FractionOfSecondParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass FractionOfSecondParser extends _Parser.Parser {\n priority = 30;\n\n parse(dateString, token) {\n const valueCallback = (value) =>\n Math.trunc(value * Math.pow(10, -token.length + 3));\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n\n set(date, _flags, value) {\n date.setMilliseconds(value);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.FractionOfSecondParser = FractionOfSecondParser;\n", "\"use strict\";\nexports.ISOTimezoneWithZParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601. +00:00 is `'Z'`)\nclass ISOTimezoneWithZParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"X\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"XX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"XXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"XXXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"XXX\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"x\"];\n}\nexports.ISOTimezoneWithZParser = ISOTimezoneWithZParser;\n", "\"use strict\";\nexports.ISOTimezoneParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601)\nclass ISOTimezoneParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"x\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"xx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"xxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"xxxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"xxx\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"X\"];\n}\nexports.ISOTimezoneParser = ISOTimezoneParser;\n", "\"use strict\";\nexports.TimestampSecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampSecondsParser extends _Parser.Parser {\n priority = 40;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [\n (0, _index.constructFrom)(date, value * 1000),\n { timestampIsSet: true },\n ];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampSecondsParser = TimestampSecondsParser;\n", "\"use strict\";\nexports.TimestampMillisecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampMillisecondsParser extends _Parser.Parser {\n priority = 20;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [(0, _index.constructFrom)(date, value), { timestampIsSet: true }];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampMillisecondsParser = TimestampMillisecondsParser;\n", "\"use strict\";\nexports.parsers = void 0;\nvar _EraParser = require(\"./parsers/EraParser.cjs\");\nvar _YearParser = require(\"./parsers/YearParser.cjs\");\nvar _LocalWeekYearParser = require(\"./parsers/LocalWeekYearParser.cjs\");\nvar _ISOWeekYearParser = require(\"./parsers/ISOWeekYearParser.cjs\");\nvar _ExtendedYearParser = require(\"./parsers/ExtendedYearParser.cjs\");\nvar _QuarterParser = require(\"./parsers/QuarterParser.cjs\");\nvar _StandAloneQuarterParser = require(\"./parsers/StandAloneQuarterParser.cjs\");\nvar _MonthParser = require(\"./parsers/MonthParser.cjs\");\nvar _StandAloneMonthParser = require(\"./parsers/StandAloneMonthParser.cjs\");\nvar _LocalWeekParser = require(\"./parsers/LocalWeekParser.cjs\");\nvar _ISOWeekParser = require(\"./parsers/ISOWeekParser.cjs\");\nvar _DateParser = require(\"./parsers/DateParser.cjs\");\nvar _DayOfYearParser = require(\"./parsers/DayOfYearParser.cjs\");\nvar _DayParser = require(\"./parsers/DayParser.cjs\");\nvar _LocalDayParser = require(\"./parsers/LocalDayParser.cjs\");\nvar _StandAloneLocalDayParser = require(\"./parsers/StandAloneLocalDayParser.cjs\");\nvar _ISODayParser = require(\"./parsers/ISODayParser.cjs\");\nvar _AMPMParser = require(\"./parsers/AMPMParser.cjs\");\nvar _AMPMMidnightParser = require(\"./parsers/AMPMMidnightParser.cjs\");\nvar _DayPeriodParser = require(\"./parsers/DayPeriodParser.cjs\");\nvar _Hour1to12Parser = require(\"./parsers/Hour1to12Parser.cjs\");\nvar _Hour0to23Parser = require(\"./parsers/Hour0to23Parser.cjs\");\nvar _Hour0To11Parser = require(\"./parsers/Hour0To11Parser.cjs\");\nvar _Hour1To24Parser = require(\"./parsers/Hour1To24Parser.cjs\");\nvar _MinuteParser = require(\"./parsers/MinuteParser.cjs\");\nvar _SecondParser = require(\"./parsers/SecondParser.cjs\");\nvar _FractionOfSecondParser = require(\"./parsers/FractionOfSecondParser.cjs\");\nvar _ISOTimezoneWithZParser = require(\"./parsers/ISOTimezoneWithZParser.cjs\");\nvar _ISOTimezoneParser = require(\"./parsers/ISOTimezoneParser.cjs\");\nvar _TimestampSecondsParser = require(\"./parsers/TimestampSecondsParser.cjs\");\nvar _TimestampMillisecondsParser = require(\"./parsers/TimestampMillisecondsParser.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O* | Timezone (GMT) |\n * | p | | P | |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n */\nconst parsers = (exports.parsers = {\n G: new _EraParser.EraParser(),\n y: new _YearParser.YearParser(),\n Y: new _LocalWeekYearParser.LocalWeekYearParser(),\n R: new _ISOWeekYearParser.ISOWeekYearParser(),\n u: new _ExtendedYearParser.ExtendedYearParser(),\n Q: new _QuarterParser.QuarterParser(),\n q: new _StandAloneQuarterParser.StandAloneQuarterParser(),\n M: new _MonthParser.MonthParser(),\n L: new _StandAloneMonthParser.StandAloneMonthParser(),\n w: new _LocalWeekParser.LocalWeekParser(),\n I: new _ISOWeekParser.ISOWeekParser(),\n d: new _DateParser.DateParser(),\n D: new _DayOfYearParser.DayOfYearParser(),\n E: new _DayParser.DayParser(),\n e: new _LocalDayParser.LocalDayParser(),\n c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(),\n i: new _ISODayParser.ISODayParser(),\n a: new _AMPMParser.AMPMParser(),\n b: new _AMPMMidnightParser.AMPMMidnightParser(),\n B: new _DayPeriodParser.DayPeriodParser(),\n h: new _Hour1to12Parser.Hour1to12Parser(),\n H: new _Hour0to23Parser.Hour0to23Parser(),\n K: new _Hour0To11Parser.Hour0To11Parser(),\n k: new _Hour1To24Parser.Hour1To24Parser(),\n m: new _MinuteParser.MinuteParser(),\n s: new _SecondParser.SecondParser(),\n S: new _FractionOfSecondParser.FractionOfSecondParser(),\n X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(),\n x: new _ISOTimezoneParser.ISOTimezoneParser(),\n t: new _TimestampSecondsParser.TimestampSecondsParser(),\n T: new _TimestampMillisecondsParser.TimestampMillisecondsParser(),\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index2.longFormatters;\n },\n});\nexports.parse = parse;\nObject.defineProperty(exports, \"parsers\", {\n enumerable: true,\n get: function () {\n return _index7.parsers;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index3 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index4 = require(\"./constructFrom.cjs\");\nvar _index5 = require(\"./getDefaultOptions.cjs\");\nvar _index6 = require(\"./toDate.cjs\");\n\nvar _Setter = require(\"./parse/_lib/Setter.cjs\");\nvar _index7 = require(\"./parse/_lib/parsers.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n/**\n * The {@link parse} function options.\n */\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\n\nconst notWhitespaceRegExp = /\\S/;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @name parse\n * @category Common Helpers\n * @summary Parse the date.\n *\n * @description\n * Return the date parsed from string using the given format string.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * parse('23 AM', 'HH a', new Date())\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Sun | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `parse` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `parse` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`\n *\n * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`\n *\n * while `uu` will just assign the year as is:\n *\n * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`\n *\n * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be assigned to the date in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),\n * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.\n *\n * `referenceDate` must be passed for correct work of the function.\n * If you're not sure which `referenceDate` to supply, create a new instance of Date:\n * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`\n * In this case parsing will be done in the context of the current date.\n * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,\n * then `Invalid Date` will be returned.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * If parsing failed, `Invalid Date` will be returned.\n * Invalid Date is a Date, whose time value is NaN.\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - The string to parse\n * @param formatStr - The string of tokens\n * @param referenceDate - defines values missing from the parsed dateString\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns The parsed date\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Parse 11 February 2014 from middle-endian format:\n * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())\n * //=> Tue Feb 11 2014 00:00:00\n *\n * @example\n * // Parse 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * var result = parse('28-a de februaro', \"do 'de' MMMM\", new Date(2010, 0, 1), {\n * locale: eo\n * })\n * //=> Sun Feb 28 2010 00:00:00\n */\nfunction parse(dateStr, formatStr, referenceDate, options) {\n const invalidDate = () =>\n (0, _index4.constructFrom)(options?.in || referenceDate, NaN);\n const defaultOptions = (0, _index5.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n if (!formatStr)\n return dateStr\n ? invalidDate()\n : (0, _index6.toDate)(referenceDate, options?.in);\n\n const subFnOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n // If timezone isn't specified, it will try to use the context or\n // the reference date and fallback to the system time zone.\n const setters = [new _Setter.DateTimezoneSetter(options?.in, referenceDate)];\n\n const tokens = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter in _index2.longFormatters) {\n const longFormatter = _index2.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp);\n\n const usedTokens = [];\n\n for (let token of tokens) {\n if (\n !options?.useAdditionalWeekYearTokens &&\n (0, _index3.isProtectedWeekYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n if (\n !options?.useAdditionalDayOfYearTokens &&\n (0, _index3.isProtectedDayOfYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n\n const firstCharacter = token[0];\n const parser = _index7.parsers[firstCharacter];\n if (parser) {\n const { incompatibleTokens } = parser;\n if (Array.isArray(incompatibleTokens)) {\n const incompatibleToken = usedTokens.find(\n (usedToken) =>\n incompatibleTokens.includes(usedToken.token) ||\n usedToken.token === firstCharacter,\n );\n if (incompatibleToken) {\n throw new RangeError(\n `The format string mustn't contain \\`${incompatibleToken.fullToken}\\` and \\`${token}\\` at the same time`,\n );\n }\n } else if (parser.incompatibleTokens === \"*\" && usedTokens.length > 0) {\n throw new RangeError(\n `The format string mustn't contain \\`${token}\\` and any other token at the same time`,\n );\n }\n\n usedTokens.push({ token: firstCharacter, fullToken: token });\n\n const parseResult = parser.run(\n dateStr,\n token,\n locale.match,\n subFnOptions,\n );\n\n if (!parseResult) {\n return invalidDate();\n }\n\n setters.push(parseResult.setter);\n\n dateStr = parseResult.rest;\n } else {\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n // Replace two single quote characters with one single quote character\n if (token === \"''\") {\n token = \"'\";\n } else if (firstCharacter === \"'\") {\n token = cleanEscapedString(token);\n }\n\n // Cut token from string, or, if string doesn't match the token, return Invalid Date\n if (dateStr.indexOf(token) === 0) {\n dateStr = dateStr.slice(token.length);\n } else {\n return invalidDate();\n }\n }\n }\n\n // Check if the remaining input contains something other than whitespace\n if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {\n return invalidDate();\n }\n\n const uniquePrioritySetters = setters\n .map((setter) => setter.priority)\n .sort((a, b) => b - a)\n .filter((priority, index, array) => array.indexOf(priority) === index)\n .map((priority) =>\n setters\n .filter((setter) => setter.priority === priority)\n .sort((a, b) => b.subPriority - a.subPriority),\n )\n .map((setterArray) => setterArray[0]);\n\n let date = (0, _index6.toDate)(referenceDate, options?.in);\n\n if (isNaN(+date)) return invalidDate();\n\n const flags = {};\n for (const setter of uniquePrioritySetters) {\n if (!setter.validate(date, subFnOptions)) {\n return invalidDate();\n }\n\n const result = setter.set(date, flags, subFnOptions);\n // Result is tuple (date, flags)\n if (Array.isArray(result)) {\n date = result[0];\n Object.assign(flags, result[1]);\n // Result is date\n } else {\n date = result;\n }\n }\n\n return date;\n}\n\nfunction cleanEscapedString(input) {\n return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.isMatch = isMatch;\nvar _index = require(\"./isValid.cjs\");\nvar _index2 = require(\"./parse.cjs\");\n\n/**\n * The {@link isMatch} function options.\n */\n\n/**\n * @name isMatch\n * @category Common Helpers\n * @summary validates the date string against given formats\n *\n * @description\n * Return the true if given date is string correct against the given format else\n * will return false.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * isMatch('23 AM', 'HH a')\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Su | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Su | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Su | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `isMatch` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `isMatch('50', 'yy') //=> true`\n *\n * `isMatch('75', 'yy') //=> true`\n *\n * while `uu` will use the year as is:\n *\n * `isMatch('50', 'uu') //=> true`\n *\n * `isMatch('75', 'uu') //=> true`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be checked in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year),\n * the values will be taken from today's using `new Date()` date which works as a context of parsing.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * @param dateStr - The date string to verify\n * @param format - The string of tokens\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns Is format string a match for date string?\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Match 11 February 2014 from middle-endian format:\n * const result = isMatch('02/11/2014', 'MM/dd/yyyy')\n * //=> true\n *\n * @example\n * // Match 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * const result = isMatch('28-a de februaro', \"do 'de' MMMM\", {\n * locale: eo\n * })\n * //=> true\n */\nfunction isMatch(dateStr, formatStr, options) {\n return (0, _index.isValid)(\n (0, _index2.parse)(dateStr, formatStr, new Date(), options),\n );\n}\n", "\"use strict\";\nexports.isMonday = isMonday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isMonday} function options.\n */\n\n/**\n * @name isMonday\n * @category Weekday Helpers\n * @summary Is the given date Monday?\n *\n * @description\n * Is the given date Monday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Monday\n *\n * @example\n * // Is 22 September 2014 Monday?\n * const result = isMonday(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isMonday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 1;\n}\n", "\"use strict\";\nexports.isPast = isPast;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isPast\n * @category Common Helpers\n * @summary Is the given date in the past?\n * @pure false\n *\n * @description\n * Is the given date in the past?\n *\n * @param date - The date to check\n *\n * @returns The date is in the past\n *\n * @example\n * // If today is 6 October 2014, is 2 July 2014 in the past?\n * const result = isPast(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isPast(date) {\n return +(0, _index.toDate)(date) < Date.now();\n}\n", "\"use strict\";\nexports.startOfHour = startOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfHour} function options.\n */\n\n/**\n * @name startOfHour\n * @category Hour Helpers\n * @summary Return the start of an hour for the given date.\n *\n * @description\n * Return the start of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an hour\n *\n * @example\n * // The start of an hour for 2 September 2014 11:55:00:\n * const result = startOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:00:00\n */\nfunction startOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.isSameHour = isSameHour;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfHour.cjs\");\n\n/**\n * The {@link isSameHour} function options.\n */\n\n/**\n * @name isSameHour\n * @category Hour Helpers\n * @summary Are the given dates in the same hour (and same day)?\n *\n * @description\n * Are the given dates in the same hour (and same day)?\n *\n * @param dateLeft - The first date to check\n * @param dateRight - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same hour (and same day)\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30))\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0))\n * //=> false\n */\nfunction isSameHour(dateLeft, dateRight, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n dateLeft,\n dateRight,\n );\n return (\n +(0, _index2.startOfHour)(dateLeft_) ===\n +(0, _index2.startOfHour)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isSameWeek = isSameWeek;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link isSameWeek} function options.\n */\n\n/**\n * @name isSameWeek\n * @category Week Helpers\n * @summary Are the given dates in the same week (and month and year)?\n *\n * @description\n * Are the given dates in the same week (and month and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same week (and month and year)\n *\n * @example\n * // Are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4))\n * //=> true\n *\n * @example\n * // If week starts with Monday,\n * // are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), {\n * weekStartsOn: 1\n * })\n * //=> false\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same week?\n * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameWeek(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfWeek)(laterDate_, options) ===\n +(0, _index2.startOfWeek)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.isSameISOWeek = isSameISOWeek;\nvar _index = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isSameISOWeek} function options.\n */\n\n/**\n * @name isSameISOWeek\n * @category ISO Week Helpers\n * @summary Are the given dates in the same ISO week (and year)?\n *\n * @description\n * Are the given dates in the same ISO week (and year)?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week (and year)\n *\n * @example\n * // Are 1 September 2014 and 7 September 2014 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7))\n * //=> true\n *\n * @example\n * // Are 1 September 2014 and 1 September 2015 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1))\n * //=> false\n */\nfunction isSameISOWeek(laterDate, earlierDate, options) {\n return (0, _index.isSameWeek)(laterDate, earlierDate, {\n ...options,\n weekStartsOn: 1,\n });\n}\n", "\"use strict\";\nexports.isSameISOWeekYear = isSameISOWeekYear;\nvar _index = require(\"./startOfISOWeekYear.cjs\");\n\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameISOWeekYear} function options.\n */\n\n/**\n * @name isSameISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Are the given dates in the same ISO week-numbering year?\n *\n * @description\n * Are the given dates in the same ISO week-numbering year?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week-numbering year\n *\n * @example\n * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year?\n * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2))\n * //=> true\n */\nfunction isSameISOWeekYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index.startOfISOWeekYear)(laterDate_) ===\n +(0, _index.startOfISOWeekYear)(earlierDate_)\n );\n}\n", "\"use strict\";\nexports.startOfMinute = startOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMinute} function options.\n */\n\n/**\n * @name startOfMinute\n * @category Minute Helpers\n * @summary Return the start of a minute for the given date.\n *\n * @description\n * Return the start of a minute for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a minute\n *\n * @example\n * // The start of a minute for 1 December 2014 22:15:45.400:\n * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:00\n */\nfunction startOfMinute(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setSeconds(0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameMinute = isSameMinute;\nvar _index = require(\"./startOfMinute.cjs\");\n\n/**\n * @name isSameMinute\n * @category Minute Helpers\n * @summary Are the given dates in the same minute (and hour and day)?\n *\n * @description\n * Are the given dates in the same minute (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same minute (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 4, 6, 30, 15)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 5 September 2014 06:30:00 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 5, 6, 30)\n * )\n * //=> false\n */\nfunction isSameMinute(laterDate, earlierDate) {\n return (\n +(0, _index.startOfMinute)(laterDate) ===\n +(0, _index.startOfMinute)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameMonth = isSameMonth;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameMonth} function options.\n */\n\n/**\n * @name isSameMonth\n * @category Month Helpers\n * @summary Are the given dates in the same month (and year)?\n *\n * @description\n * Are the given dates in the same month (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same month (and year)\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n *\n * @example\n * // Are 2 September 2014 and 25 September 2015 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))\n * //=> false\n */\nfunction isSameMonth(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n laterDate_.getFullYear() === earlierDate_.getFullYear() &&\n laterDate_.getMonth() === earlierDate_.getMonth()\n );\n}\n", "\"use strict\";\nexports.isSameQuarter = isSameQuarter;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link isSameQuarter} function options.\n */\n\n/**\n * @name isSameQuarter\n * @category Quarter Helpers\n * @summary Are the given dates in the same quarter (and year)?\n *\n * @description\n * Are the given dates in the same quarter (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same quarter (and year)\n *\n * @example\n * // Are 1 January 2014 and 8 March 2014 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8))\n * //=> true\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameQuarter(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfQuarter)(dateLeft_) ===\n +(0, _index2.startOfQuarter)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.startOfSecond = startOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfSecond} function options.\n */\n\n/**\n * @name startOfSecond\n * @category Second Helpers\n * @summary Return the start of a second for the given date.\n *\n * @description\n * Return the start of a second for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a second\n *\n * @example\n * // The start of a second for 1 December 2014 22:15:45.400:\n * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.000\n */\nfunction startOfSecond(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMilliseconds(0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameSecond = isSameSecond;\nvar _index = require(\"./startOfSecond.cjs\");\n\n/**\n * @name isSameSecond\n * @category Second Helpers\n * @summary Are the given dates in the same second (and hour and day)?\n *\n * @description\n * Are the given dates in the same second (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same second (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 30, 15),\n * new Date(2014, 8, 4, 6, 30, 15, 500)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 4 September 2014 06:01.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 4, 6, 1, 15)\n * )\n * //=> false\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 5 September 2014 06:00.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 5, 6, 0, 15)\n * )\n * //=> false\n */\nfunction isSameSecond(laterDate, earlierDate) {\n return (\n +(0, _index.startOfSecond)(laterDate) ===\n +(0, _index.startOfSecond)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameYear = isSameYear;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameYear} function options.\n */\n\n/**\n * @name isSameYear\n * @category Year Helpers\n * @summary Are the given dates in the same year?\n *\n * @description\n * Are the given dates in the same year?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same year\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same year?\n * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n */\nfunction isSameYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() === earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.isThisHour = isThisHour;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameHour.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThisHour} function options.\n */\n\n/**\n * @name isThisHour\n * @category Hour Helpers\n * @summary Is the given date in the same hour as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same hour as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this hour\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:00:00 in this hour?\n * const result = isThisHour(new Date(2014, 8, 25, 18))\n * //=> true\n */\nfunction isThisHour(date, options) {\n return (0, _index2.isSameHour)(\n (0, _index3.toDate)(date, options?.in),\n (0, _index.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisISOWeek = isThisISOWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameISOWeek.cjs\");\n\n/**\n * The {@link isThisISOWeek} function options.\n */\n\n/**\n * @name isThisISOWeek\n * @category ISO Week Helpers\n * @summary Is the given date in the same ISO week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same ISO week as the current date?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this ISO week\n *\n * @example\n * // If today is 25 September 2014, is 22 September 2014 in this ISO week?\n * const result = isThisISOWeek(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isThisISOWeek(date, options) {\n return (0, _index3.isSameISOWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisMinute = isThisMinute;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameMinute.cjs\");\n\n/**\n * @name isThisMinute\n * @category Minute Helpers\n * @summary Is the given date in the same minute as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same minute as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this minute\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:00 in this minute?\n * const result = isThisMinute(new Date(2014, 8, 25, 18, 30))\n * //=> true\n */\n\nfunction isThisMinute(date) {\n return (0, _index2.isSameMinute)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisMonth = isThisMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameMonth.cjs\");\n\n/**\n * The {@link isThisMonth} function options.\n */\n\n/**\n * @name isThisMonth\n * @category Month Helpers\n * @summary Is the given date in the same month as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same month as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this month\n *\n * @example\n * // If today is 25 September 2014, is 15 September 2014 in this month?\n * const result = isThisMonth(new Date(2014, 8, 15))\n * //=> true\n */\nfunction isThisMonth(date, options) {\n return (0, _index3.isSameMonth)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisQuarter = isThisQuarter;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameQuarter.cjs\");\n\n/**\n * The {@link isThisQuarter} function options.\n */\n\n/**\n * @name isThisQuarter\n * @category Quarter Helpers\n * @summary Is the given date in the same quarter as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same quarter as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this quarter\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this quarter?\n * const result = isThisQuarter(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisQuarter(date, options) {\n return (0, _index3.isSameQuarter)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisSecond = isThisSecond;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameSecond.cjs\");\n\n/**\n * @name isThisSecond\n * @category Second Helpers\n * @summary Is the given date in the same second as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same second as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this second\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:15.000 in this second?\n * const result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15))\n * //=> true\n */\nfunction isThisSecond(date) {\n return (0, _index2.isSameSecond)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisWeek = isThisWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isThisWeek} function options.\n */\n\n/**\n * @name isThisWeek\n * @category Week Helpers\n * @summary Is the given date in the same week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same week as the current date?\n *\n * @param date - The date to check\n * @param options - The object with options\n *\n * @returns The date is in this week\n *\n * @example\n * // If today is 25 September 2014, is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21))\n * //=> true\n *\n * @example\n * // If today is 25 September 2014 and week starts with Monday\n * // is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21), { weekStartsOn: 1 })\n * //=> false\n */\nfunction isThisWeek(date, options) {\n return (0, _index3.isSameWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n options,\n );\n}\n", "\"use strict\";\nexports.isThisYear = isThisYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameYear.cjs\");\n\n/**\n * The {@link isThisYear} function options.\n */\n\n/**\n * @name isThisYear\n * @category Year Helpers\n * @summary Is the given date in the same year as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same year as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this year\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this year?\n * const result = isThisYear(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisYear(date, options) {\n return (0, _index3.isSameYear)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThursday = isThursday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThursday} function options.\n */\n\n/**\n * @name isThursday\n * @category Weekday Helpers\n * @summary Is the given date Thursday?\n *\n * @description\n * Is the given date Thursday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Thursday\n *\n * @example\n * // Is 25 September 2014 Thursday?\n * const result = isThursday(new Date(2014, 8, 25))\n * //=> true\n */\nfunction isThursday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 4;\n}\n", "\"use strict\";\nexports.isToday = isToday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isToday} function options.\n */\n\n/**\n * @name isToday\n * @category Day Helpers\n * @summary Is the given date today?\n * @pure false\n *\n * @description\n * Is the given date today?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is today\n *\n * @example\n * // If today is 6 October 2014, is 6 October 14:00:00 today?\n * const result = isToday(new Date(2014, 9, 6, 14, 0))\n * //=> true\n */\nfunction isToday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isTomorrow = isTomorrow;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isTomorrow} function options.\n */\n\n/**\n * @name isTomorrow\n * @category Day Helpers\n * @summary Is the given date tomorrow?\n * @pure false\n *\n * @description\n * Is the given date tomorrow?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is tomorrow\n *\n * @example\n * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow?\n * const result = isTomorrow(new Date(2014, 9, 7, 14, 0))\n * //=> true\n */\nfunction isTomorrow(date, options) {\n return (0, _index3.isSameDay)(\n date,\n (0, _index.addDays)((0, _index2.constructNow)(options?.in || date), 1),\n options,\n );\n}\n", "\"use strict\";\nexports.isTuesday = isTuesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isTuesday} function options.\n */\n\n/**\n * @name isTuesday\n * @category Weekday Helpers\n * @summary Is the given date Tuesday?\n *\n * @description\n * Is the given date Tuesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Tuesday\n *\n * @example\n * // Is 23 September 2014 Tuesday?\n * const result = isTuesday(new Date(2014, 8, 23))\n * //=> true\n */\nfunction isTuesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 2;\n}\n", "\"use strict\";\nexports.isWednesday = isWednesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWednesday} function options.\n */\n\n/**\n * @name isWednesday\n * @category Weekday Helpers\n * @summary Is the given date Wednesday?\n *\n * @description\n * Is the given date Wednesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Wednesday\n *\n * @example\n * // Is 24 September 2014 Wednesday?\n * const result = isWednesday(new Date(2014, 8, 24))\n * //=> true\n */\nfunction isWednesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 3;\n}\n", "\"use strict\";\nexports.isWithinInterval = isWithinInterval;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWithinInterval} function options.\n */\n\n/**\n * @name isWithinInterval\n * @category Interval Helpers\n * @summary Is the given date within the interval?\n *\n * @description\n * Is the given date within the interval? (Including start and end.)\n *\n * @param date - The date to check\n * @param interval - The interval to check\n * @param options - An object with options\n *\n * @returns The date is within the interval\n *\n * @example\n * // For the date within the interval:\n * isWithinInterval(new Date(2014, 0, 3), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => true\n *\n * @example\n * // For the date outside of the interval:\n * isWithinInterval(new Date(2014, 0, 10), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => false\n *\n * @example\n * // For date equal to the interval start:\n * isWithinInterval(date, { start, end: date })\n * // => true\n *\n * @example\n * // For date equal to the interval end:\n * isWithinInterval(date, { start: date, end })\n * // => true\n */\nfunction isWithinInterval(date, interval, options) {\n const time = +(0, _index.toDate)(date, options?.in);\n const [startTime, endTime] = [\n +(0, _index.toDate)(interval.start, options?.in),\n +(0, _index.toDate)(interval.end, options?.in),\n ].sort((a, b) => a - b);\n\n return time >= startTime && time <= endTime;\n}\n", "\"use strict\";\nexports.subDays = subDays;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link subDays} function options.\n */\n\n/**\n * @name subDays\n * @category Day Helpers\n * @summary Subtract the specified number of days from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the days subtracted\n *\n * @example\n * // Subtract 10 days from 1 September 2014:\n * const result = subDays(new Date(2014, 8, 1), 10)\n * //=> Fri Aug 22 2014 00:00:00\n */\nfunction subDays(date, amount, options) {\n return (0, _index.addDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.isYesterday = isYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\nvar _index4 = require(\"./subDays.cjs\");\n\n/**\n * The {@link isYesterday} function options.\n */\n\n/**\n * @name isYesterday\n * @category Day Helpers\n * @summary Is the given date yesterday?\n * @pure false\n *\n * @description\n * Is the given date yesterday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is yesterday\n *\n * @example\n * // If today is 6 October 2014, is 5 October 14:00:00 yesterday?\n * const result = isYesterday(new Date(2014, 9, 5, 14, 0))\n * //=> true\n */\nfunction isYesterday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index4.subDays)((0, _index2.constructNow)(options?.in || date), 1),\n );\n}\n", "\"use strict\";\nexports.lastDayOfDecade = lastDayOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfDecade} function options.\n */\n\n/**\n * @name lastDayOfDecade\n * @category Decade Helpers\n * @summary Return the last day of a decade for the given date.\n *\n * @description\n * Return the last day of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type; inferred from arguments or specified by context.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a decade\n *\n * @example\n * // The last day of a decade for 21 December 2012 21:12:00:\n * const result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00))\n * //=> Wed Dec 31 2019 00:00:00\n */\nfunction lastDayOfDecade(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade + 1, 0, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.lastDayOfWeek = lastDayOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfWeek} function options.\n */\n\n/**\n * @name lastDayOfWeek\n * @category Week Helpers\n * @summary Return the last day of a week for the given date.\n *\n * @description\n * Return the last day of a week for the given date.\n * The result will be in the local timezone unless a context is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a week\n */\nfunction lastDayOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setHours(0, 0, 0, 0);\n _date.setDate(_date.getDate() + diff);\n\n return _date;\n}\n", "\"use strict\";\nexports.lastDayOfISOWeek = lastDayOfISOWeek;\nvar _index = require(\"./lastDayOfWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeek} function options.\n */\n\n/**\n * @name lastDayOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the last day of an ISO week for the given date.\n *\n * @description\n * Return the last day of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of an ISO week\n *\n * @example\n * // The last day of an ISO week for 2 September 2014 11:55:00:\n * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction lastDayOfISOWeek(date, options) {\n return (0, _index.lastDayOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.lastDayOfISOWeekYear = lastDayOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeekYear} function options.\n */\n\n/**\n * @name lastDayOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the last day of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the last day of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The last day of an ISO week-numbering year for 2 July 2005:\n * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 00:00:00\n */\nfunction lastDayOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year + 1, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index3.startOfISOWeek)(fourthOfJanuary, options);\n date_.setDate(date_.getDate() - 1);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfQuarter = lastDayOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfQuarter} function options.\n */\n\n/**\n * @name lastDayOfQuarter\n * @category Quarter Helpers\n * @summary Return the last day of a year quarter for the given date.\n *\n * @description\n * Return the last day of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a quarter\n *\n * @example\n * // The last day of a quarter for 2 September 2014 11:55:00:\n * const result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfQuarter(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const currentMonth = date_.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n date_.setMonth(month, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfYear = lastDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfYear} function options.\n */\n\n/**\n * @name lastDayOfYear\n * @category Year Helpers\n * @summary Return the last day of a year for the given date.\n *\n * @description\n * Return the last day of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a year\n *\n * @example\n * // The last day of a year for 2 September 2014 11:55:00:\n * const result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Dec 31 2014 00:00:00\n */\nfunction lastDayOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const year = date_.getFullYear();\n date_.setFullYear(year + 1, 0, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lightFormat = lightFormat;\nObject.defineProperty(exports, \"lightFormatters\", {\n enumerable: true,\n get: function () {\n return _index.lightFormatters;\n },\n});\nvar _index = require(\"./_lib/format/lightFormatters.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp = /(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @private\n */\n\n/**\n * @name lightFormat\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. Unlike `format`,\n * `lightFormat` doesn't use locales and outputs date using the most popular tokens.\n *\n * > \u26A0\uFE0F Please note that the `lightFormat` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples |\n * |---------------------------------|---------|-----------------------------------|\n * | AM, PM | a..aaa | AM, PM |\n * | | aaaa | a.m., p.m. |\n * | | aaaaa | a, p |\n * | Calendar year | y | 44, 1, 1900, 2017 |\n * | | yy | 44, 01, 00, 17 |\n * | | yyy | 044, 001, 000, 017 |\n * | | yyyy | 0044, 0001, 1900, 2017 |\n * | Month (formatting) | M | 1, 2, ..., 12 |\n * | | MM | 01, 02, ..., 12 |\n * | Day of month | d | 1, 2, ..., 31 |\n * | | dd | 01, 02, ..., 31 |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 |\n * | | hh | 01, 02, ..., 11, 12 |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 |\n * | | HH | 00, 01, 02, ..., 23 |\n * | Minute | m | 0, 1, ..., 59 |\n * | | mm | 00, 01, ..., 59 |\n * | Second | s | 0, 1, ..., 59 |\n * | | ss | 00, 01, ..., 59 |\n * | Fraction of second | S | 0, 1, ..., 9 |\n * | | SS | 00, 01, ..., 99 |\n * | | SSS | 000, 001, ..., 999 |\n * | | SSSS | ... |\n *\n * @param date - The original date\n * @param format - The string of tokens\n *\n * @returns The formatted date string\n *\n * @throws `Invalid time value` if the date is invalid\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd')\n * //=> '2014-02-11'\n */\nfunction lightFormat(date, formatStr) {\n const date_ = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const tokens = formatStr.match(formattingTokensRegExp);\n\n // The only case when formattingTokensRegExp doesn't match the string is when it's empty\n if (!tokens) return \"\";\n\n const result = tokens\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return \"'\";\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return cleanEscapedString(substring);\n }\n\n const formatter = _index.lightFormatters[firstCharacter];\n if (formatter) {\n return formatter(date_, substring);\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return substring;\n })\n .join(\"\");\n\n return result;\n}\n\nfunction cleanEscapedString(input) {\n const matches = input.match(escapedStringRegExp);\n if (!matches) return input;\n return matches[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.milliseconds = milliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name milliseconds\n * @category Millisecond Helpers\n * @summary\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * @description\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n *\n * One month is a year divided by 12.\n *\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.\n *\n * @returns The milliseconds\n *\n * @example\n * // 1 year in milliseconds\n * milliseconds({ years: 1 })\n * //=> 31556952000\n *\n * // 3 months in milliseconds\n * milliseconds({ months: 3 })\n * //=> 7889238000\n */\nfunction milliseconds({ years, months, weeks, days, hours, minutes, seconds }) {\n let totalDays = 0;\n\n if (years) totalDays += years * _index.daysInYear;\n if (months) totalDays += months * (_index.daysInYear / 12);\n if (weeks) totalDays += weeks * 7;\n if (days) totalDays += days;\n\n let totalSeconds = totalDays * 24 * 60 * 60;\n\n if (hours) totalSeconds += hours * 60 * 60;\n if (minutes) totalSeconds += minutes * 60;\n if (seconds) totalSeconds += seconds;\n\n return Math.trunc(totalSeconds * 1000);\n}\n", "\"use strict\";\nexports.millisecondsToHours = millisecondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToHours\n * @category Conversion Helpers\n * @summary Convert milliseconds to hours.\n *\n * @description\n * Convert a number of milliseconds to a full number of hours.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in hours\n *\n * @example\n * // Convert 7200000 milliseconds to hours:\n * const result = millisecondsToHours(7200000)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToHours(7199999)\n * //=> 1\n */\nfunction millisecondsToHours(milliseconds) {\n const hours = milliseconds / _index.millisecondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.millisecondsToMinutes = millisecondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToMinutes\n * @category Conversion Helpers\n * @summary Convert milliseconds to minutes.\n *\n * @description\n * Convert a number of milliseconds to a full number of minutes.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in minutes\n *\n * @example\n * // Convert 60000 milliseconds to minutes:\n * const result = millisecondsToMinutes(60000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToMinutes(119999)\n * //=> 1\n */\nfunction millisecondsToMinutes(milliseconds) {\n const minutes = milliseconds / _index.millisecondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.millisecondsToSeconds = millisecondsToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToSeconds\n * @category Conversion Helpers\n * @summary Convert milliseconds to seconds.\n *\n * @description\n * Convert a number of milliseconds to a full number of seconds.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in seconds\n *\n * @example\n * // Convert 1000 milliseconds to seconds:\n * const result = millisecondsToSeconds(1000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToSeconds(1999)\n * //=> 1\n */\nfunction millisecondsToSeconds(milliseconds) {\n const seconds = milliseconds / _index.millisecondsInSecond;\n return Math.trunc(seconds);\n}\n", "\"use strict\";\nexports.minutesToHours = minutesToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToHours\n * @category Conversion Helpers\n * @summary Convert minutes to hours.\n *\n * @description\n * Convert a number of minutes to a full number of hours.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in hours\n *\n * @example\n * // Convert 140 minutes to hours:\n * const result = minutesToHours(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = minutesToHours(179)\n * //=> 2\n */\nfunction minutesToHours(minutes) {\n const hours = minutes / _index.minutesInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.minutesToMilliseconds = minutesToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToMilliseconds\n * @category Conversion Helpers\n * @summary Convert minutes to milliseconds.\n *\n * @description\n * Convert a number of minutes to a full number of milliseconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in milliseconds\n *\n * @example\n * // Convert 2 minutes to milliseconds\n * const result = minutesToMilliseconds(2)\n * //=> 120000\n */\nfunction minutesToMilliseconds(minutes) {\n return Math.trunc(minutes * _index.millisecondsInMinute);\n}\n", "\"use strict\";\nexports.minutesToSeconds = minutesToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToSeconds\n * @category Conversion Helpers\n * @summary Convert minutes to seconds.\n *\n * @description\n * Convert a number of minutes to a full number of seconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in seconds\n *\n * @example\n * // Convert 2 minutes to seconds\n * const result = minutesToSeconds(2)\n * //=> 120\n */\nfunction minutesToSeconds(minutes) {\n return Math.trunc(minutes * _index.secondsInMinute);\n}\n", "\"use strict\";\nexports.monthsToQuarters = monthsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToQuarters\n * @category Conversion Helpers\n * @summary Convert number of months to quarters.\n *\n * @description\n * Convert a number of months to a full number of quarters.\n *\n * @param months - The number of months to be converted.\n *\n * @returns The number of months converted in quarters\n *\n * @example\n * // Convert 6 months to quarters:\n * const result = monthsToQuarters(6)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = monthsToQuarters(7)\n * //=> 2\n */\nfunction monthsToQuarters(months) {\n const quarters = months / _index.monthsInQuarter;\n return Math.trunc(quarters);\n}\n", "\"use strict\";\nexports.monthsToYears = monthsToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToYears\n * @category Conversion Helpers\n * @summary Convert number of months to years.\n *\n * @description\n * Convert a number of months to a full number of years.\n *\n * @param months - The number of months to be converted\n *\n * @returns The number of months converted in years\n *\n * @example\n * // Convert 36 months to years:\n * const result = monthsToYears(36)\n * //=> 3\n *\n * // It uses floor rounding:\n * const result = monthsToYears(40)\n * //=> 3\n */\nfunction monthsToYears(months) {\n const years = months / _index.monthsInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.nextDay = nextDay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getDay.cjs\");\n\n/**\n * The {@link nextDay} function options.\n */\n\n/**\n * @name nextDay\n * @category Weekday Helpers\n * @summary When is the next day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - Day of the week\n * @param options - An object with options\n *\n * @returns The date is the next day of the week\n *\n * @example\n * // When is the next Monday after Mar, 20, 2020?\n * const result = nextDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 23 2020 00:00:00\n *\n * @example\n * // When is the next Tuesday after Mar, 21, 2020?\n * const result = nextDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextDay(date, day, options) {\n let delta = day - (0, _index2.getDay)(date, options);\n if (delta <= 0) delta += 7;\n\n return (0, _index.addDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.nextFriday = nextFriday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextFriday} function options.\n */\n\n/**\n * @name nextFriday\n * @category Weekday Helpers\n * @summary When is the next Friday?\n *\n * @description\n * When is the next Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Friday\n *\n * @example\n * // When is the next Friday after Mar, 22, 2020?\n * const result = nextFriday(new Date(2020, 2, 22))\n * //=> Fri Mar 27 2020 00:00:00\n */\nfunction nextFriday(date, options) {\n return (0, _index.nextDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.nextMonday = nextMonday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextMonday} function options.\n */\n\n/**\n * @name nextMonday\n * @category Weekday Helpers\n * @summary When is the next Monday?\n *\n * @description\n * When is the next Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function if passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Monday\n *\n * @example\n * // When is the next Monday after Mar, 22, 2020?\n * const result = nextMonday(new Date(2020, 2, 22))\n * //=> Mon Mar 23 2020 00:00:00\n */\nfunction nextMonday(date, options) {\n return (0, _index.nextDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.nextSaturday = nextSaturday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSaturday} function options.\n */\n\n/**\n * @name nextSaturday\n * @category Weekday Helpers\n * @summary When is the next Saturday?\n *\n * @description\n * When is the next Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Saturday\n *\n * @example\n * // When is the next Saturday after Mar, 22, 2020?\n * const result = nextSaturday(new Date(2020, 2, 22))\n * //=> Sat Mar 28 2020 00:00:00\n */\nfunction nextSaturday(date, options) {\n return (0, _index.nextDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.nextSunday = nextSunday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSunday} function options.\n */\n\n/**\n * @name nextSunday\n * @category Weekday Helpers\n * @summary When is the next Sunday?\n *\n * @description\n * When is the next Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned if a context is provided.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Sunday\n *\n * @example\n * // When is the next Sunday after March 22, 2020?\n * const result = nextSunday(new Date(2020, 2, 22))\n * //=> Sun Mar 29 2020 00:00:00\n */\nfunction nextSunday(date, options) {\n return (0, _index.nextDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.nextThursday = nextThursday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextThursday} function options.\n */\n\n/**\n * @name nextThursday\n * @category Weekday Helpers\n * @summary When is the next Thursday?\n *\n * @description\n * When is the next Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Thursday\n *\n * @example\n * // When is the next Thursday after Mar, 22, 2020?\n * const result = nextThursday(new Date(2020, 2, 22))\n * //=> Thur Mar 26 2020 00:00:00\n */\nfunction nextThursday(date, options) {\n return (0, _index.nextDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.nextTuesday = nextTuesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextTuesday} function options.\n */\n\n/**\n * @name nextTuesday\n * @category Weekday Helpers\n * @summary When is the next Tuesday?\n *\n * @description\n * When is the next Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Tuesday\n *\n * @example\n * // When is the next Tuesday after Mar, 22, 2020?\n * const result = nextTuesday(new Date(2020, 2, 22))\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextTuesday(date, options) {\n return (0, _index.nextDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.nextWednesday = nextWednesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextWednesday} function options.\n */\n\n/**\n * @name nextWednesday\n * @category Weekday Helpers\n * @summary When is the next Wednesday?\n *\n * @description\n * When is the next Wednesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Wednesday\n *\n * @example\n * // When is the next Wednesday after Mar, 22, 2020?\n * const result = nextWednesday(new Date(2020, 2, 22))\n * //=> Wed Mar 25 2020 00:00:00\n */\nfunction nextWednesday(date, options) {\n return (0, _index.nextDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.parseISO = parseISO;\nvar _index = require(\"./constants.cjs\");\n\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseISO} function options.\n */\n\n/**\n * @name parseISO\n * @category Common Helpers\n * @summary Parse ISO string\n *\n * @description\n * Parse the given string in ISO 8601 format and return an instance of Date.\n *\n * Function accepts complete ISO 8601 formats as well as partial implementations.\n * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601\n *\n * If the argument isn't a string, the function cannot parse the string or\n * the values are invalid, it returns Invalid Date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Convert string '2014-02-11T11:30:30' to date:\n * const result = parseISO('2014-02-11T11:30:30')\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert string '+02014101' to date,\n * // if the additional number of digits in the extended year format is 1:\n * const result = parseISO('+02014101', { additionalDigits: 1 })\n * //=> Fri Apr 11 2014 00:00:00\n */\nfunction parseISO(argument, options) {\n const invalidDate = () => (0, _index2.constructFrom)(options?.in, NaN);\n\n const additionalDigits = options?.additionalDigits ?? 2;\n const dateStrings = splitDateString(argument);\n\n let date;\n if (dateStrings.date) {\n const parseYearResult = parseYear(dateStrings.date, additionalDigits);\n date = parseDate(parseYearResult.restDateString, parseYearResult.year);\n }\n\n if (!date || isNaN(+date)) return invalidDate();\n\n const timestamp = +date;\n let time = 0;\n let offset;\n\n if (dateStrings.time) {\n time = parseTime(dateStrings.time);\n if (isNaN(time)) return invalidDate();\n }\n\n if (dateStrings.timezone) {\n offset = parseTimezone(dateStrings.timezone);\n if (isNaN(offset)) return invalidDate();\n } else {\n const tmpDate = new Date(timestamp + time);\n const result = (0, _index3.toDate)(0, options?.in);\n result.setFullYear(\n tmpDate.getUTCFullYear(),\n tmpDate.getUTCMonth(),\n tmpDate.getUTCDate(),\n );\n result.setHours(\n tmpDate.getUTCHours(),\n tmpDate.getUTCMinutes(),\n tmpDate.getUTCSeconds(),\n tmpDate.getUTCMilliseconds(),\n );\n return result;\n }\n\n return (0, _index3.toDate)(timestamp + time + offset, options?.in);\n}\n\nconst patterns = {\n dateTimeDelimiter: /[T ]/,\n timeZoneDelimiter: /[Z ]/i,\n timezone: /([Z+-].*)$/,\n};\n\nconst dateRegex =\n /^-?(?:(\\d{3})|(\\d{2})(?:-?(\\d{2}))?|W(\\d{2})(?:-?(\\d{1}))?|)$/;\nconst timeRegex =\n /^(\\d{2}(?:[.,]\\d*)?)(?::?(\\d{2}(?:[.,]\\d*)?))?(?::?(\\d{2}(?:[.,]\\d*)?))?$/;\nconst timezoneRegex = /^([+-])(\\d{2})(?::?(\\d{2}))?$/;\n\nfunction splitDateString(dateString) {\n const dateStrings = {};\n const array = dateString.split(patterns.dateTimeDelimiter);\n let timeString;\n\n // The regex match should only return at maximum two array elements.\n // [date], [time], or [date, time].\n if (array.length > 2) {\n return dateStrings;\n }\n\n if (/:/.test(array[0])) {\n timeString = array[0];\n } else {\n dateStrings.date = array[0];\n timeString = array[1];\n if (patterns.timeZoneDelimiter.test(dateStrings.date)) {\n dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];\n timeString = dateString.substr(\n dateStrings.date.length,\n dateString.length,\n );\n }\n }\n\n if (timeString) {\n const token = patterns.timezone.exec(timeString);\n if (token) {\n dateStrings.time = timeString.replace(token[1], \"\");\n dateStrings.timezone = token[1];\n } else {\n dateStrings.time = timeString;\n }\n }\n\n return dateStrings;\n}\n\nfunction parseYear(dateString, additionalDigits) {\n const regex = new RegExp(\n \"^(?:(\\\\d{4}|[+-]\\\\d{\" +\n (4 + additionalDigits) +\n \"})|(\\\\d{2}|[+-]\\\\d{\" +\n (2 + additionalDigits) +\n \"})$)\",\n );\n\n const captures = dateString.match(regex);\n // Invalid ISO-formatted year\n if (!captures) return { year: NaN, restDateString: \"\" };\n\n const year = captures[1] ? parseInt(captures[1]) : null;\n const century = captures[2] ? parseInt(captures[2]) : null;\n\n // either year or century is null, not both\n return {\n year: century === null ? year : century * 100,\n restDateString: dateString.slice((captures[1] || captures[2]).length),\n };\n}\n\nfunction parseDate(dateString, year) {\n // Invalid ISO-formatted year\n if (year === null) return new Date(NaN);\n\n const captures = dateString.match(dateRegex);\n // Invalid ISO-formatted string\n if (!captures) return new Date(NaN);\n\n const isWeekDate = !!captures[4];\n const dayOfYear = parseDateUnit(captures[1]);\n const month = parseDateUnit(captures[2]) - 1;\n const day = parseDateUnit(captures[3]);\n const week = parseDateUnit(captures[4]);\n const dayOfWeek = parseDateUnit(captures[5]) - 1;\n\n if (isWeekDate) {\n if (!validateWeekDate(year, week, dayOfWeek)) {\n return new Date(NaN);\n }\n return dayOfISOWeekYear(year, week, dayOfWeek);\n } else {\n const date = new Date(0);\n if (\n !validateDate(year, month, day) ||\n !validateDayOfYearDate(year, dayOfYear)\n ) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, month, Math.max(dayOfYear, day));\n return date;\n }\n}\n\nfunction parseDateUnit(value) {\n return value ? parseInt(value) : 1;\n}\n\nfunction parseTime(timeString) {\n const captures = timeString.match(timeRegex);\n if (!captures) return NaN; // Invalid ISO-formatted time\n\n const hours = parseTimeUnit(captures[1]);\n const minutes = parseTimeUnit(captures[2]);\n const seconds = parseTimeUnit(captures[3]);\n\n if (!validateTime(hours, minutes, seconds)) {\n return NaN;\n }\n\n return (\n hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * 1000\n );\n}\n\nfunction parseTimeUnit(value) {\n return (value && parseFloat(value.replace(\",\", \".\"))) || 0;\n}\n\nfunction parseTimezone(timezoneString) {\n if (timezoneString === \"Z\") return 0;\n\n const captures = timezoneString.match(timezoneRegex);\n if (!captures) return 0;\n\n const sign = captures[1] === \"+\" ? -1 : 1;\n const hours = parseInt(captures[2]);\n const minutes = (captures[3] && parseInt(captures[3])) || 0;\n\n if (!validateTimezone(hours, minutes)) {\n return NaN;\n }\n\n return (\n sign *\n (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute)\n );\n}\n\nfunction dayOfISOWeekYear(isoWeekYear, week, day) {\n const date = new Date(0);\n date.setUTCFullYear(isoWeekYear, 0, 4);\n const fourthOfJanuaryDay = date.getUTCDay() || 7;\n const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;\n date.setUTCDate(date.getUTCDate() + diff);\n return date;\n}\n\n// Validation functions\n\n// February is null to handle the leap year (using ||)\nconst daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n\nfunction validateDate(year, month, date) {\n return (\n month >= 0 &&\n month <= 11 &&\n date >= 1 &&\n date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28))\n );\n}\n\nfunction validateDayOfYearDate(year, dayOfYear) {\n return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);\n}\n\nfunction validateWeekDate(_year, week, day) {\n return week >= 1 && week <= 53 && day >= 0 && day <= 6;\n}\n\nfunction validateTime(hours, minutes, seconds) {\n if (hours === 24) {\n return minutes === 0 && seconds === 0;\n }\n\n return (\n seconds >= 0 &&\n seconds < 60 &&\n minutes >= 0 &&\n minutes < 60 &&\n hours >= 0 &&\n hours < 25\n );\n}\n\nfunction validateTimezone(_hours, minutes) {\n return minutes >= 0 && minutes <= 59;\n}\n", "\"use strict\";\nexports.parseJSON = parseJSON;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseJSON} function options.\n */\n\n/**\n * Converts a complete ISO date string in UTC time, the typical format for transmitting\n * a date in JSON, to a JavaScript `Date` instance.\n *\n * This is a minimal implementation for converting dates retrieved from a JSON API to\n * a `Date` instance which can be used with other functions in the `date-fns` library.\n * The following formats are supported:\n *\n * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`\n * - `2000-03-15T05:20:10Z`: Without milliseconds\n * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon\n * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol\n * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds\n * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting\n *\n * For convenience and ease of use these other input types are also supported\n * via [toDate](https://date-fns.org/docs/toDate):\n *\n * - A `Date` instance will be cloned\n * - A `number` will be treated as a timestamp\n *\n * Any other input type or invalid date strings will return an `Invalid Date`.\n *\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - A fully formed ISO8601 date string to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n */\nfunction parseJSON(dateStr, options) {\n const parts = dateStr.match(\n /(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{0,7}))?(?:Z|(.)(\\d{2}):?(\\d{2})?)?/,\n );\n\n if (!parts) return (0, _index.toDate)(NaN, options?.in);\n\n return (0, _index.toDate)(\n Date.UTC(\n +parts[1],\n +parts[2] - 1,\n +parts[3],\n +parts[4] - (+parts[9] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[5] - (+parts[10] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[6],\n +((parts[7] || \"0\") + \"00\").substring(0, 3),\n ),\n options?.in,\n );\n}\n", "\"use strict\";\nexports.previousDay = previousDay;\nvar _index = require(\"./getDay.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\n\n/**\n * The {@link previousDay} function options.\n */\n\n/**\n * @name previousDay\n * @category Weekday Helpers\n * @summary When is the previous day of the week?\n *\n * @description\n * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - The day of the week\n * @param options - An object with options\n *\n * @returns The date is the previous day of week\n *\n * @example\n * // When is the previous Monday before Mar, 20, 2020?\n * const result = previousDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 16 2020 00:00:00\n *\n * @example\n * // When is the previous Tuesday before Mar, 21, 2020?\n * const result = previousDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 17 2020 00:00:00\n */\nfunction previousDay(date, day, options) {\n let delta = (0, _index.getDay)(date, options) - day;\n if (delta <= 0) delta += 7;\n\n return (0, _index2.subDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.previousFriday = previousFriday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousFriday} function options.\n */\n\n/**\n * @name previousFriday\n * @category Weekday Helpers\n * @summary When is the previous Friday?\n *\n * @description\n * When is the previous Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Friday\n *\n * @example\n * // When is the previous Friday before Jun, 19, 2021?\n * const result = previousFriday(new Date(2021, 5, 19))\n * //=> Fri June 18 2021 00:00:00\n */\nfunction previousFriday(date, options) {\n return (0, _index.previousDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.previousMonday = previousMonday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousMonday} function options.\n */\n\n/**\n * @name previousMonday\n * @category Weekday Helpers\n * @summary When is the previous Monday?\n *\n * @description\n * When is the previous Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Monday\n *\n * @example\n * // When is the previous Monday before Jun, 18, 2021?\n * const result = previousMonday(new Date(2021, 5, 18))\n * //=> Mon June 14 2021 00:00:00\n */\nfunction previousMonday(date, options) {\n return (0, _index.previousDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.previousSaturday = previousSaturday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSaturday} function options.\n */\n\n/**\n * @name previousSaturday\n * @category Weekday Helpers\n * @summary When is the previous Saturday?\n *\n * @description\n * When is the previous Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Saturday\n *\n * @example\n * // When is the previous Saturday before Jun, 20, 2021?\n * const result = previousSaturday(new Date(2021, 5, 20))\n * //=> Sat June 19 2021 00:00:00\n */\nfunction previousSaturday(date, options) {\n return (0, _index.previousDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.previousSunday = previousSunday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSunday} function options.\n */\n\n/**\n * @name previousSunday\n * @category Weekday Helpers\n * @summary When is the previous Sunday?\n *\n * @description\n * When is the previous Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Sunday\n *\n * @example\n * // When is the previous Sunday before Jun, 21, 2021?\n * const result = previousSunday(new Date(2021, 5, 21))\n * //=> Sun June 20 2021 00:00:00\n */\nfunction previousSunday(date, options) {\n return (0, _index.previousDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.previousThursday = previousThursday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousThursday} function options.\n */\n\n/**\n * @name previousThursday\n * @category Weekday Helpers\n * @summary When is the previous Thursday?\n *\n * @description\n * When is the previous Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Thursday\n *\n * @example\n * // When is the previous Thursday before Jun, 18, 2021?\n * const result = previousThursday(new Date(2021, 5, 18))\n * //=> Thu June 17 2021 00:00:00\n */\nfunction previousThursday(date, options) {\n return (0, _index.previousDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.previousTuesday = previousTuesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousTuesday} function options.\n */\n\n/**\n * @name previousTuesday\n * @category Weekday Helpers\n * @summary When is the previous Tuesday?\n *\n * @description\n * When is the previous Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Tuesday\n *\n * @example\n * // When is the previous Tuesday before Jun, 18, 2021?\n * const result = previousTuesday(new Date(2021, 5, 18))\n * //=> Tue June 15 2021 00:00:00\n */\nfunction previousTuesday(date, options) {\n return (0, _index.previousDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.previousWednesday = previousWednesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousWednesday} function options.\n */\n\n/**\n * @name previousWednesday\n * @category Weekday Helpers\n * @summary When is the previous Wednesday?\n *\n * @description\n * When is the previous Wednesday?\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Wednesday\n *\n * @example\n * // When is the previous Wednesday before Jun, 18, 2021?\n * const result = previousWednesday(new Date(2021, 5, 18))\n * //=> Wed June 16 2021 00:00:00\n */\nfunction previousWednesday(date, options) {\n return (0, _index.previousDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.quartersToMonths = quartersToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToMonths\n * @category Conversion Helpers\n * @summary Convert number of quarters to months.\n *\n * @description\n * Convert a number of quarters to a full number of months.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in months\n *\n * @example\n * // Convert 2 quarters to months\n * const result = quartersToMonths(2)\n * //=> 6\n */\nfunction quartersToMonths(quarters) {\n return Math.trunc(quarters * _index.monthsInQuarter);\n}\n", "\"use strict\";\nexports.quartersToYears = quartersToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToYears\n * @category Conversion Helpers\n * @summary Convert number of quarters to years.\n *\n * @description\n * Convert a number of quarters to a full number of years.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in years\n *\n * @example\n * // Convert 8 quarters to years\n * const result = quartersToYears(8)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = quartersToYears(11)\n * //=> 2\n */\nfunction quartersToYears(quarters) {\n const years = quarters / _index.quartersInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.roundToNearestHours = roundToNearestHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestHours} function options.\n */\n\n/**\n * @name roundToNearestHours\n * @category Hour Helpers\n * @summary Rounds the given date to the nearest hour\n *\n * @description\n * Rounds the given date to the nearest hour (or number of hours).\n * Rounds up when the given date is exactly between the nearest round hours.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest hour\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56))\n * //=> Thu Jul 10 2014 13:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 6 })\n * //=> Thu Jul 10 2014 12:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 8 })\n * //=> Thu Jul 10 2014 16:00:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 1, 23, 45), { roundingMethod: 'ceil' })\n * //=> Thu Jul 10 2014 02:00:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:34:56 to nearest quarter hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { roundingMethod: 'floor', nearestTo: 8 })\n * //=> Thu Jul 10 2014 08:00:00\n */\nfunction roundToNearestHours(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 12)\n return (0, _index2.constructFrom)(options?.in || date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalMinutes = date_.getMinutes() / 60;\n const fractionalSeconds = date_.getSeconds() / 60 / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60 / 60;\n const hours =\n date_.getHours() +\n fractionalMinutes +\n fractionalSeconds +\n fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedHours = roundingMethod(hours / nearestTo) * nearestTo;\n\n date_.setHours(roundedHours, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.roundToNearestMinutes = roundToNearestMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestMinutes} function options.\n */\n\n/**\n * @name roundToNearestMinutes\n * @category Minute Helpers\n * @summary Rounds the given date to the nearest minute\n *\n * @description\n * Rounds the given date to the nearest minute (or number of minutes).\n * Rounds up when the given date is exactly between the nearest round minutes.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest minute\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))\n * //=> Thu Jul 10 2014 12:13:00\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest quarter hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })\n * //=> Thu Jul 10 2014 12:15:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'floor' })\n * //=> Thu Jul 10 2014 12:12:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:12:34 to nearest half hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'ceil', nearestTo: 30 })\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction roundToNearestMinutes(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 30)\n return (0, _index2.constructFrom)(date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalSeconds = date_.getSeconds() / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60;\n const minutes =\n date_.getMinutes() + fractionalSeconds + fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;\n\n date_.setMinutes(roundedMinutes, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.secondsToHours = secondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToHours\n * @category Conversion Helpers\n * @summary Convert seconds to hours.\n *\n * @description\n * Convert a number of seconds to a full number of hours.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in hours\n *\n * @example\n * // Convert 7200 seconds into hours\n * const result = secondsToHours(7200)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToHours(7199)\n * //=> 1\n */\nfunction secondsToHours(seconds) {\n const hours = seconds / _index.secondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.secondsToMilliseconds = secondsToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMilliseconds\n * @category Conversion Helpers\n * @summary Convert seconds to milliseconds.\n *\n * @description\n * Convert a number of seconds to a full number of milliseconds.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in milliseconds\n *\n * @example\n * // Convert 2 seconds into milliseconds\n * const result = secondsToMilliseconds(2)\n * //=> 2000\n */\nfunction secondsToMilliseconds(seconds) {\n return seconds * _index.millisecondsInSecond;\n}\n", "\"use strict\";\nexports.secondsToMinutes = secondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMinutes\n * @category Conversion Helpers\n * @summary Convert seconds to minutes.\n *\n * @description\n * Convert a number of seconds to a full number of minutes.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in minutes\n *\n * @example\n * // Convert 120 seconds into minutes\n * const result = secondsToMinutes(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToMinutes(119)\n * //=> 1\n */\nfunction secondsToMinutes(seconds) {\n const minutes = seconds / _index.secondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.setMonth = setMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getDaysInMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMonth} function options.\n */\n\n/**\n * @name setMonth\n * @category Month Helpers\n * @summary Set the month to the given date.\n *\n * @description\n * Set the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param month - The month index to set (0-11)\n * @param options - The options\n *\n * @returns The new date with the month set\n *\n * @example\n * // Set February to 1 September 2014:\n * const result = setMonth(new Date(2014, 8, 1), 1)\n * //=> Sat Feb 01 2014 00:00:00\n */\nfunction setMonth(date, month, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const day = _date.getDate();\n\n const midMonth = (0, _index.constructFrom)(options?.in || date, 0);\n midMonth.setFullYear(year, month, 15);\n midMonth.setHours(0, 0, 0, 0);\n const daysInMonth = (0, _index2.getDaysInMonth)(midMonth);\n\n // Set the earlier date, allows to wrap Jan 31 to Feb 28\n _date.setMonth(month, Math.min(day, daysInMonth));\n return _date;\n}\n", "\"use strict\";\nexports.set = set;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./setMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link set} function options.\n */\n\n/**\n * @name set\n * @category Common Helpers\n * @summary Set date values to a given date.\n *\n * @description\n * Set date values to a given date.\n *\n * Sets time values to date from object `values`.\n * A value is not set if it is undefined or null or doesn't exist in `values`.\n *\n * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts\n * to use native `Date#setX` methods. If you use this function, you may not want to include the\n * other `setX` functions that date-fns provides if you are concerned about the bundle size.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param values - The date values to be set\n * @param options - The options\n *\n * @returns The new date with options set\n *\n * @example\n * // Transform 1 September 2014 into 20 October 2015 in a single line:\n * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })\n * //=> Tue Oct 20 2015 00:00:00\n *\n * @example\n * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:\n * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })\n * //=> Mon Sep 01 2014 12:23:45\n */\nfunction set(date, values, options) {\n let _date = (0, _index3.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+_date)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n if (values.year != null) _date.setFullYear(values.year);\n if (values.month != null) _date = (0, _index2.setMonth)(_date, values.month);\n if (values.date != null) _date.setDate(values.date);\n if (values.hours != null) _date.setHours(values.hours);\n if (values.minutes != null) _date.setMinutes(values.minutes);\n if (values.seconds != null) _date.setSeconds(values.seconds);\n if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);\n\n return _date;\n}\n", "\"use strict\";\nexports.setDate = setDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDate} function options.\n */\n\n/**\n * @name setDate\n * @category Day Helpers\n * @summary Set the day of the month to the given date.\n *\n * @description\n * Set the day of the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfMonth - The day of the month of the new date\n * @param options - The options\n *\n * @returns The new date with the day of the month set\n *\n * @example\n * // Set the 30th day of the month to 1 September 2014:\n * const result = setDate(new Date(2014, 8, 1), 30)\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction setDate(date, dayOfMonth, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(dayOfMonth);\n return _date;\n}\n", "\"use strict\";\nexports.setDayOfYear = setDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDayOfYear} function options.\n */\n\n/**\n * @name setDayOfYear\n * @category Day Helpers\n * @summary Set the day of the year to the given date.\n *\n * @description\n * Set the day of the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfYear - The day of the year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the year set\n *\n * @example\n * // Set the 2nd day of the year to 2 July 2014:\n * const result = setDayOfYear(new Date(2014, 6, 2), 2)\n * //=> Thu Jan 02 2014 00:00:00\n */\nfunction setDayOfYear(date, dayOfYear, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMonth(0);\n date_.setDate(dayOfYear);\n return date_;\n}\n", "\"use strict\";\nexports.setDefaultOptions = setDefaultOptions;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name setDefaultOptions\n * @category Common Helpers\n * @summary Set default options including locale.\n * @pure false\n *\n * @description\n * Sets the defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * @param options - An object with options\n *\n * @example\n * // Set global locale:\n * import { es } from 'date-fns/locale'\n * setDefaultOptions({ locale: es })\n * const result = format(new Date(2014, 8, 2), 'PPPP')\n * //=> 'martes, 2 de septiembre de 2014'\n *\n * @example\n * // Start of the week for 2 September 2014:\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Start of the week for 2 September 2014,\n * // when we set that week starts on Monday by default:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Mon Sep 01 2014 00:00:00\n *\n * @example\n * // Manually set options take priority over default options:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 })\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Remove the option by setting it to `undefined`:\n * setDefaultOptions({ weekStartsOn: 1 })\n * setDefaultOptions({ weekStartsOn: undefined })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n */\nfunction setDefaultOptions(options) {\n const result = {};\n const defaultOptions = (0, _index.getDefaultOptions)();\n\n for (const property in defaultOptions) {\n if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) {\n // [TODO] I challenge you to fix the type\n result[property] = defaultOptions[property];\n }\n }\n\n for (const property in options) {\n if (Object.prototype.hasOwnProperty.call(options, property)) {\n if (options[property] === undefined) {\n // [TODO] I challenge you to fix the type\n delete result[property];\n } else {\n // [TODO] I challenge you to fix the type\n result[property] = options[property];\n }\n }\n }\n\n (0, _index.setDefaultOptions)(result);\n}\n", "\"use strict\";\nexports.setHours = setHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setHours} function options.\n */\n\n/**\n * @name setHours\n * @category Hour Helpers\n * @summary Set the hours to the given date.\n *\n * @description\n * Set the hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param hours - The hours of the new date\n * @param options - An object with options\n *\n * @returns The new date with the hours set\n *\n * @example\n * // Set 4 hours to 1 September 2014 11:30:00:\n * const result = setHours(new Date(2014, 8, 1, 11, 30), 4)\n * //=> Mon Sep 01 2014 04:30:00\n */\nfunction setHours(date, hours, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(hours);\n return _date;\n}\n", "\"use strict\";\nexports.setMilliseconds = setMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMilliseconds} function options.\n */\n\n/**\n * @name setMilliseconds\n * @category Millisecond Helpers\n * @summary Set the milliseconds to the given date.\n *\n * @description\n * Set the milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param milliseconds - The milliseconds of the new date\n * @param options - The options\n *\n * @returns The new date with the milliseconds set\n *\n * @example\n * // Set 300 milliseconds to 1 September 2014 11:30:40.500:\n * const result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300)\n * //=> Mon Sep 01 2014 11:30:40.300\n */\nfunction setMilliseconds(date, milliseconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(milliseconds);\n return _date;\n}\n", "\"use strict\";\nexports.setMinutes = setMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMinutes} function options.\n */\n\n/**\n * @name setMinutes\n * @category Minute Helpers\n * @summary Set the minutes to the given date.\n *\n * @description\n * Set the minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param minutes - The minutes of the new date\n * @param options - An object with options\n *\n * @returns The new date with the minutes set\n *\n * @example\n * // Set 45 minutes to 1 September 2014 11:30:40:\n * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:45:40\n */\nfunction setMinutes(date, minutes, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMinutes(minutes);\n return date_;\n}\n", "\"use strict\";\nexports.setQuarter = setQuarter;\nvar _index = require(\"./setMonth.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setQuarter} function options.\n */\n\n/**\n * @name setQuarter\n * @category Quarter Helpers\n * @summary Set the year quarter to the given date.\n *\n * @description\n * Set the year quarter to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param quarter - The quarter of the new date\n * @param options - The options\n *\n * @returns The new date with the quarter set\n *\n * @example\n * // Set the 2nd quarter to 2 July 2014:\n * const result = setQuarter(new Date(2014, 6, 2), 2)\n * //=> Wed Apr 02 2014 00:00:00\n */\nfunction setQuarter(date, quarter, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const oldQuarter = Math.trunc(date_.getMonth() / 3) + 1;\n const diff = quarter - oldQuarter;\n return (0, _index.setMonth)(date_, date_.getMonth() + diff * 3);\n}\n", "\"use strict\";\nexports.setSeconds = setSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setSeconds} function options.\n */\n\n/**\n * @name setSeconds\n * @category Second Helpers\n * @summary Set the seconds to the given date, with context support.\n *\n * @description\n * Set the seconds to the given date, with an optional context for time zone specification.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param seconds - The seconds of the new date\n * @param options - An object with options\n *\n * @returns The new date with the seconds set\n *\n * @example\n * // Set 45 seconds to 1 September 2014 11:30:40:\n * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:30:45\n */\nfunction setSeconds(date, seconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(seconds);\n return _date;\n}\n", "\"use strict\";\nexports.setWeekYear = setWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./startOfWeekYear.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeekYear} function options.\n */\n\n/**\n * @name setWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Set the local week-numbering year to the given date.\n *\n * @description\n * Set the local week-numbering year to the given date,\n * saving the week number and the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The local week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week-numbering year set\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010 with default options:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004)\n * //=> Sat Jan 03 2004 00:00:00\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010,\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setWeekYear(date, weekYear, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const diff = (0, _index3.differenceInCalendarDays)(\n (0, _index5.toDate)(date, options?.in),\n (0, _index4.startOfWeekYear)(date, options),\n options,\n );\n\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index4.startOfWeekYear)(firstWeek, options);\n date_.setDate(date_.getDate() + diff);\n return date_;\n}\n", "\"use strict\";\nexports.setYear = setYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setYear} function options.\n */\n\n/**\n * @name setYear\n * @category Year Helpers\n * @summary Set the year to the given date.\n *\n * @description\n * Set the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param year - The year of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the year set\n *\n * @example\n * // Set year 2013 to 1 September 2014:\n * const result = setYear(new Date(2014, 8, 1), 2013)\n * //=> Sun Sep 01 2013 00:00:00\n */\nfunction setYear(date, year, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+date_)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n date_.setFullYear(year);\n return date_;\n}\n", "\"use strict\";\nexports.startOfDecade = startOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDecade} options.\n */\n\n/**\n * @name startOfDecade\n * @category Decade Helpers\n * @summary Return the start of a decade for the given date.\n *\n * @description\n * Return the start of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a decade\n *\n * @example\n * // The start of a decade for 21 October 2015 00:00:00:\n * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))\n * //=> Jan 01 2010 00:00:00\n */\nfunction startOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 0, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfToday = startOfToday;\nvar _index = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link startOfToday} function options.\n */\n\n/**\n * @name startOfToday\n * @category Day Helpers\n * @summary Return the start of today.\n * @pure false\n *\n * @description\n * Return the start of today.\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfToday()\n * //=> Mon Oct 6 2014 00:00:00\n */\nfunction startOfToday(options) {\n return (0, _index.startOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.startOfTomorrow = startOfTomorrow;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfTomorrow} function options.\n */\n\n/**\n * @name startOfTomorrow\n * @category Day Helpers\n * @summary Return the start of tomorrow.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of tomorrow\n *\n * @description\n * Return the start of tomorrow.\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfTomorrow()\n * //=> Tue Oct 7 2014 00:00:00\n */\nfunction startOfTomorrow(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.startOfYesterday = startOfYesterday;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfYesterday} function options.\n */\n\n/**\n * @name startOfYesterday\n * @category Day Helpers\n * @summary Return the start of yesterday.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @description\n * Return the start of yesterday.\n *\n * @returns The start of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfYesterday()\n * //=> Sun Oct 5 2014 00:00:00\n */\nfunction startOfYesterday(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day - 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.subMonths = subMonths;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The subMonths function options.\n */\n\n/**\n * @name subMonths\n * @category Month Helpers\n * @summary Subtract the specified number of months from the given date.\n *\n * @description\n * Subtract the specified number of months from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the months subtracted\n *\n * @example\n * // Subtract 5 months from 1 February 2015:\n * const result = subMonths(new Date(2015, 1, 1), 5)\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction subMonths(date, amount, options) {\n return (0, _index.addMonths)(date, -amount, options);\n}\n", "\"use strict\";\nexports.sub = sub;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\nvar _index3 = require(\"./subMonths.cjs\");\n\n/**\n * The {@link sub} function options.\n */\n\n/**\n * @name sub\n * @category Common Helpers\n * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @description\n * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be subtracted\n * @param options - An object with options\n *\n * | Key | Description |\n * |---------|------------------------------------|\n * | years | Amount of years to be subtracted |\n * | months | Amount of months to be subtracted |\n * | weeks | Amount of weeks to be subtracted |\n * | days | Amount of days to be subtracted |\n * | hours | Amount of hours to be subtracted |\n * | minutes | Amount of minutes to be subtracted |\n * | seconds | Amount of seconds to be subtracted |\n *\n * All values default to 0\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract the following duration from 15 June 2017 15:29:20\n * const result = sub(new Date(2017, 5, 15, 15, 29, 20), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> Mon Sep 1 2014 10:19:50\n */\nfunction sub(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n const withoutMonths = (0, _index3.subMonths)(\n date,\n months + years * 12,\n options,\n );\n const withoutDays = (0, _index2.subDays)(\n withoutMonths,\n days + weeks * 7,\n options,\n );\n\n const minutesToSub = minutes + hours * 60;\n const secondsToSub = seconds + minutesToSub * 60;\n const msToSub = secondsToSub * 1000;\n\n return (0, _index.constructFrom)(options?.in || date, +withoutDays - msToSub);\n}\n", "\"use strict\";\nexports.subBusinessDays = subBusinessDays;\nvar _index = require(\"./addBusinessDays.cjs\");\n\n/**\n * The {@link subBusinessDays} function options.\n */\n\n/**\n * @name subBusinessDays\n * @category Day Helpers\n * @summary Subtract the specified number of business days (mon - fri) from the given date.\n *\n * @description\n * Subtract the specified number of business days (mon - fri) from the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the business days subtracted\n *\n * @example\n * // Subtract 10 business days from 1 September 2014:\n * const result = subBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Aug 18 2014 00:00:00 (skipped weekend days)\n */\nfunction subBusinessDays(date, amount, options) {\n return (0, _index.addBusinessDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subHours = subHours;\nvar _index = require(\"./addHours.cjs\");\n\n/**\n * The {@link subHours} function options.\n */\n\n/**\n * @name subHours\n * @category Hour Helpers\n * @summary Subtract the specified number of hours from the given date.\n *\n * @description\n * Subtract the specified number of hours from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the hours subtracted\n *\n * @example\n * // Subtract 2 hours from 11 July 2014 01:00:00:\n * const result = subHours(new Date(2014, 6, 11, 1, 0), 2)\n * //=> Thu Jul 10 2014 23:00:00\n */\nfunction subHours(date, amount, options) {\n return (0, _index.addHours)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMilliseconds = subMilliseconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link subMilliseconds} function options.\n */\n\n/**\n * Subtract the specified number of milliseconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the milliseconds subtracted\n */\nfunction subMilliseconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMinutes = subMinutes;\nvar _index = require(\"./addMinutes.cjs\");\n\n/**\n * The {@link subMinutes} function options.\n */\n\n/**\n * @name subMinutes\n * @category Minute Helpers\n * @summary Subtract the specified number of minutes from the given date.\n *\n * @description\n * Subtract the specified number of minutes from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the minutes subtracted\n *\n * @example\n * // Subtract 30 minutes from 10 July 2014 12:00:00:\n * const result = subMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 11:30:00\n */\nfunction subMinutes(date, amount, options) {\n return (0, _index.addMinutes)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subQuarters = subQuarters;\nvar _index = require(\"./addQuarters.cjs\");\n\n/**\n * The {@link subQuarters} function options.\n */\n\n/**\n * @name subQuarters\n * @category Quarter Helpers\n * @summary Subtract the specified number of year quarters from the given date.\n *\n * @description\n * Subtract the specified number of year quarters from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the quarters subtracted\n *\n * @example\n * // Subtract 3 quarters from 1 September 2014:\n * const result = subQuarters(new Date(2014, 8, 1), 3)\n * //=> Sun Dec 01 2013 00:00:00\n */\nfunction subQuarters(date, amount, options) {\n return (0, _index.addQuarters)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subSeconds = subSeconds;\nvar _index = require(\"./addSeconds.cjs\");\n\n/**\n * The {@link subSeconds} function options.\n */\n\n/**\n * Subtract the specified number of seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract 30 seconds from 10 July 2014 12:45:00:\n * const result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:44:30\n */\nfunction subSeconds(date, amount, options) {\n return (0, _index.addSeconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subWeeks = subWeeks;\nvar _index = require(\"./addWeeks.cjs\");\n\n/**\n * The {@link subWeeks} function options.\n */\n\n/**\n * @name subWeeks\n * @category Week Helpers\n * @summary Subtract the specified number of weeks from the given date.\n *\n * @description\n * Subtract the specified number of weeks from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the weeks subtracted\n *\n * @example\n * // Subtract 4 weeks from 1 September 2014:\n * const result = subWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Aug 04 2014 00:00:00\n */\nfunction subWeeks(date, amount, options) {\n return (0, _index.addWeeks)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subYears = subYears;\nvar _index = require(\"./addYears.cjs\");\n\n/**\n * The {@link subYears} function options.\n */\n\n/**\n * @name subYears\n * @category Year Helpers\n * @summary Subtract the specified number of years from the given date.\n *\n * @description\n * Subtract the specified number of years from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the years subtracted\n *\n * @example\n * // Subtract 5 years from 1 September 2014:\n * const result = subYears(new Date(2014, 8, 1), 5)\n * //=> Tue Sep 01 2009 00:00:00\n */\nfunction subYears(date, amount, options) {\n return (0, _index.addYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.weeksToDays = weeksToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name weeksToDays\n * @category Conversion Helpers\n * @summary Convert weeks to days.\n *\n * @description\n * Convert a number of weeks to a full number of days.\n *\n * @param weeks - The number of weeks to be converted\n *\n * @returns The number of weeks converted in days\n *\n * @example\n * // Convert 2 weeks into days\n * const result = weeksToDays(2)\n * //=> 14\n */\nfunction weeksToDays(weeks) {\n return Math.trunc(weeks * _index.daysInWeek);\n}\n", "\"use strict\";\nexports.yearsToDays = yearsToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToDays\n * @category Conversion Helpers\n * @summary Convert years to days.\n *\n * @description\n * Convert a number of years to a full number of days.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in days\n *\n * @example\n * // Convert 2 years into days\n * const result = yearsToDays(2)\n * //=> 730\n */\nfunction yearsToDays(years) {\n return Math.trunc(years * _index.daysInYear);\n}\n", "\"use strict\";\nexports.yearsToMonths = yearsToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToMonths\n * @category Conversion Helpers\n * @summary Convert years to months.\n *\n * @description\n * Convert a number of years to a full number of months.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in months\n *\n * @example\n * // Convert 2 years into months\n * const result = yearsToMonths(2)\n * //=> 24\n */\nfunction yearsToMonths(years) {\n return Math.trunc(years * _index.monthsInYear);\n}\n", "\"use strict\";\nexports.yearsToQuarters = yearsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToQuarters\n * @category Conversion Helpers\n * @summary Convert years to quarters.\n *\n * @description\n * Convert a number of years to a full number of quarters.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in quarters\n *\n * @example\n * // Convert 2 years to quarters\n * const result = yearsToQuarters(2)\n * //=> 8\n */\nfunction yearsToQuarters(years) {\n return Math.trunc(years * _index.quartersInYear);\n}\n", "\"use strict\";\n\nvar _index = require(\"./add.cjs\");\nObject.keys(_index).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index[key];\n },\n });\n});\nvar _index2 = require(\"./addBusinessDays.cjs\");\nObject.keys(_index2).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index2[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index2[key];\n },\n });\n});\nvar _index3 = require(\"./addDays.cjs\");\nObject.keys(_index3).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index3[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index3[key];\n },\n });\n});\nvar _index4 = require(\"./addHours.cjs\");\nObject.keys(_index4).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index4[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index4[key];\n },\n });\n});\nvar _index5 = require(\"./addISOWeekYears.cjs\");\nObject.keys(_index5).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index5[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index5[key];\n },\n });\n});\nvar _index6 = require(\"./addMilliseconds.cjs\");\nObject.keys(_index6).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index6[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index6[key];\n },\n });\n});\nvar _index7 = require(\"./addMinutes.cjs\");\nObject.keys(_index7).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index7[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index7[key];\n },\n });\n});\nvar _index8 = require(\"./addMonths.cjs\");\nObject.keys(_index8).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index8[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index8[key];\n },\n });\n});\nvar _index9 = require(\"./addQuarters.cjs\");\nObject.keys(_index9).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index9[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index9[key];\n },\n });\n});\nvar _index10 = require(\"./addSeconds.cjs\");\nObject.keys(_index10).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index10[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index10[key];\n },\n });\n});\nvar _index11 = require(\"./addWeeks.cjs\");\nObject.keys(_index11).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index11[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index11[key];\n },\n });\n});\nvar _index12 = require(\"./addYears.cjs\");\nObject.keys(_index12).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index12[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index12[key];\n },\n });\n});\nvar _index13 = require(\"./areIntervalsOverlapping.cjs\");\nObject.keys(_index13).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index13[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index13[key];\n },\n });\n});\nvar _index14 = require(\"./clamp.cjs\");\nObject.keys(_index14).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index14[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index14[key];\n },\n });\n});\nvar _index15 = require(\"./closestIndexTo.cjs\");\nObject.keys(_index15).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index15[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index15[key];\n },\n });\n});\nvar _index16 = require(\"./closestTo.cjs\");\nObject.keys(_index16).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index16[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index16[key];\n },\n });\n});\nvar _index17 = require(\"./compareAsc.cjs\");\nObject.keys(_index17).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index17[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index17[key];\n },\n });\n});\nvar _index18 = require(\"./compareDesc.cjs\");\nObject.keys(_index18).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index18[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index18[key];\n },\n });\n});\nvar _index19 = require(\"./constructFrom.cjs\");\nObject.keys(_index19).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index19[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index19[key];\n },\n });\n});\nvar _index20 = require(\"./constructNow.cjs\");\nObject.keys(_index20).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index20[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index20[key];\n },\n });\n});\nvar _index21 = require(\"./daysToWeeks.cjs\");\nObject.keys(_index21).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index21[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index21[key];\n },\n });\n});\nvar _index22 = require(\"./differenceInBusinessDays.cjs\");\nObject.keys(_index22).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index22[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index22[key];\n },\n });\n});\nvar _index23 = require(\"./differenceInCalendarDays.cjs\");\nObject.keys(_index23).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index23[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index23[key];\n },\n });\n});\nvar _index24 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nObject.keys(_index24).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index24[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index24[key];\n },\n });\n});\nvar _index25 = require(\"./differenceInCalendarISOWeeks.cjs\");\nObject.keys(_index25).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index25[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index25[key];\n },\n });\n});\nvar _index26 = require(\"./differenceInCalendarMonths.cjs\");\nObject.keys(_index26).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index26[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index26[key];\n },\n });\n});\nvar _index27 = require(\"./differenceInCalendarQuarters.cjs\");\nObject.keys(_index27).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index27[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index27[key];\n },\n });\n});\nvar _index28 = require(\"./differenceInCalendarWeeks.cjs\");\nObject.keys(_index28).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index28[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index28[key];\n },\n });\n});\nvar _index29 = require(\"./differenceInCalendarYears.cjs\");\nObject.keys(_index29).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index29[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index29[key];\n },\n });\n});\nvar _index30 = require(\"./differenceInDays.cjs\");\nObject.keys(_index30).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index30[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index30[key];\n },\n });\n});\nvar _index31 = require(\"./differenceInHours.cjs\");\nObject.keys(_index31).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index31[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index31[key];\n },\n });\n});\nvar _index32 = require(\"./differenceInISOWeekYears.cjs\");\nObject.keys(_index32).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index32[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index32[key];\n },\n });\n});\nvar _index33 = require(\"./differenceInMilliseconds.cjs\");\nObject.keys(_index33).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index33[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index33[key];\n },\n });\n});\nvar _index34 = require(\"./differenceInMinutes.cjs\");\nObject.keys(_index34).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index34[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index34[key];\n },\n });\n});\nvar _index35 = require(\"./differenceInMonths.cjs\");\nObject.keys(_index35).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index35[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index35[key];\n },\n });\n});\nvar _index36 = require(\"./differenceInQuarters.cjs\");\nObject.keys(_index36).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index36[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index36[key];\n },\n });\n});\nvar _index37 = require(\"./differenceInSeconds.cjs\");\nObject.keys(_index37).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index37[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index37[key];\n },\n });\n});\nvar _index38 = require(\"./differenceInWeeks.cjs\");\nObject.keys(_index38).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index38[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index38[key];\n },\n });\n});\nvar _index39 = require(\"./differenceInYears.cjs\");\nObject.keys(_index39).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index39[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index39[key];\n },\n });\n});\nvar _index40 = require(\"./eachDayOfInterval.cjs\");\nObject.keys(_index40).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index40[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index40[key];\n },\n });\n});\nvar _index41 = require(\"./eachHourOfInterval.cjs\");\nObject.keys(_index41).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index41[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index41[key];\n },\n });\n});\nvar _index42 = require(\"./eachMinuteOfInterval.cjs\");\nObject.keys(_index42).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index42[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index42[key];\n },\n });\n});\nvar _index43 = require(\"./eachMonthOfInterval.cjs\");\nObject.keys(_index43).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index43[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index43[key];\n },\n });\n});\nvar _index44 = require(\"./eachQuarterOfInterval.cjs\");\nObject.keys(_index44).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index44[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index44[key];\n },\n });\n});\nvar _index45 = require(\"./eachWeekOfInterval.cjs\");\nObject.keys(_index45).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index45[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index45[key];\n },\n });\n});\nvar _index46 = require(\"./eachWeekendOfInterval.cjs\");\nObject.keys(_index46).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index46[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index46[key];\n },\n });\n});\nvar _index47 = require(\"./eachWeekendOfMonth.cjs\");\nObject.keys(_index47).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index47[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index47[key];\n },\n });\n});\nvar _index48 = require(\"./eachWeekendOfYear.cjs\");\nObject.keys(_index48).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index48[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index48[key];\n },\n });\n});\nvar _index49 = require(\"./eachYearOfInterval.cjs\");\nObject.keys(_index49).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index49[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index49[key];\n },\n });\n});\nvar _index50 = require(\"./endOfDay.cjs\");\nObject.keys(_index50).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index50[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index50[key];\n },\n });\n});\nvar _index51 = require(\"./endOfDecade.cjs\");\nObject.keys(_index51).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index51[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index51[key];\n },\n });\n});\nvar _index52 = require(\"./endOfHour.cjs\");\nObject.keys(_index52).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index52[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index52[key];\n },\n });\n});\nvar _index53 = require(\"./endOfISOWeek.cjs\");\nObject.keys(_index53).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index53[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index53[key];\n },\n });\n});\nvar _index54 = require(\"./endOfISOWeekYear.cjs\");\nObject.keys(_index54).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index54[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index54[key];\n },\n });\n});\nvar _index55 = require(\"./endOfMinute.cjs\");\nObject.keys(_index55).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index55[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index55[key];\n },\n });\n});\nvar _index56 = require(\"./endOfMonth.cjs\");\nObject.keys(_index56).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index56[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index56[key];\n },\n });\n});\nvar _index57 = require(\"./endOfQuarter.cjs\");\nObject.keys(_index57).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index57[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index57[key];\n },\n });\n});\nvar _index58 = require(\"./endOfSecond.cjs\");\nObject.keys(_index58).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index58[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index58[key];\n },\n });\n});\nvar _index59 = require(\"./endOfToday.cjs\");\nObject.keys(_index59).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index59[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index59[key];\n },\n });\n});\nvar _index60 = require(\"./endOfTomorrow.cjs\");\nObject.keys(_index60).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index60[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index60[key];\n },\n });\n});\nvar _index61 = require(\"./endOfWeek.cjs\");\nObject.keys(_index61).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index61[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index61[key];\n },\n });\n});\nvar _index62 = require(\"./endOfYear.cjs\");\nObject.keys(_index62).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index62[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index62[key];\n },\n });\n});\nvar _index63 = require(\"./endOfYesterday.cjs\");\nObject.keys(_index63).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index63[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index63[key];\n },\n });\n});\nvar _index64 = require(\"./format.cjs\");\nObject.keys(_index64).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index64[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index64[key];\n },\n });\n});\nvar _index65 = require(\"./formatDistance.cjs\");\nObject.keys(_index65).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index65[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index65[key];\n },\n });\n});\nvar _index66 = require(\"./formatDistanceStrict.cjs\");\nObject.keys(_index66).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index66[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index66[key];\n },\n });\n});\nvar _index67 = require(\"./formatDistanceToNow.cjs\");\nObject.keys(_index67).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index67[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index67[key];\n },\n });\n});\nvar _index68 = require(\"./formatDistanceToNowStrict.cjs\");\nObject.keys(_index68).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index68[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index68[key];\n },\n });\n});\nvar _index69 = require(\"./formatDuration.cjs\");\nObject.keys(_index69).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index69[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index69[key];\n },\n });\n});\nvar _index70 = require(\"./formatISO.cjs\");\nObject.keys(_index70).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index70[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index70[key];\n },\n });\n});\nvar _index71 = require(\"./formatISO9075.cjs\");\nObject.keys(_index71).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index71[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index71[key];\n },\n });\n});\nvar _index72 = require(\"./formatISODuration.cjs\");\nObject.keys(_index72).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index72[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index72[key];\n },\n });\n});\nvar _index73 = require(\"./formatRFC3339.cjs\");\nObject.keys(_index73).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index73[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index73[key];\n },\n });\n});\nvar _index74 = require(\"./formatRFC7231.cjs\");\nObject.keys(_index74).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index74[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index74[key];\n },\n });\n});\nvar _index75 = require(\"./formatRelative.cjs\");\nObject.keys(_index75).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index75[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index75[key];\n },\n });\n});\nvar _index76 = require(\"./fromUnixTime.cjs\");\nObject.keys(_index76).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index76[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index76[key];\n },\n });\n});\nvar _index77 = require(\"./getDate.cjs\");\nObject.keys(_index77).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index77[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index77[key];\n },\n });\n});\nvar _index78 = require(\"./getDay.cjs\");\nObject.keys(_index78).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index78[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index78[key];\n },\n });\n});\nvar _index79 = require(\"./getDayOfYear.cjs\");\nObject.keys(_index79).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index79[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index79[key];\n },\n });\n});\nvar _index80 = require(\"./getDaysInMonth.cjs\");\nObject.keys(_index80).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index80[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index80[key];\n },\n });\n});\nvar _index81 = require(\"./getDaysInYear.cjs\");\nObject.keys(_index81).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index81[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index81[key];\n },\n });\n});\nvar _index82 = require(\"./getDecade.cjs\");\nObject.keys(_index82).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index82[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index82[key];\n },\n });\n});\nvar _index83 = require(\"./getDefaultOptions.cjs\");\nObject.keys(_index83).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index83[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index83[key];\n },\n });\n});\nvar _index84 = require(\"./getHours.cjs\");\nObject.keys(_index84).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index84[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index84[key];\n },\n });\n});\nvar _index85 = require(\"./getISODay.cjs\");\nObject.keys(_index85).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index85[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index85[key];\n },\n });\n});\nvar _index86 = require(\"./getISOWeek.cjs\");\nObject.keys(_index86).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index86[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index86[key];\n },\n });\n});\nvar _index87 = require(\"./getISOWeekYear.cjs\");\nObject.keys(_index87).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index87[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index87[key];\n },\n });\n});\nvar _index88 = require(\"./getISOWeeksInYear.cjs\");\nObject.keys(_index88).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index88[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index88[key];\n },\n });\n});\nvar _index89 = require(\"./getMilliseconds.cjs\");\nObject.keys(_index89).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index89[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index89[key];\n },\n });\n});\nvar _index90 = require(\"./getMinutes.cjs\");\nObject.keys(_index90).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index90[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index90[key];\n },\n });\n});\nvar _index91 = require(\"./getMonth.cjs\");\nObject.keys(_index91).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index91[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index91[key];\n },\n });\n});\nvar _index92 = require(\"./getOverlappingDaysInIntervals.cjs\");\nObject.keys(_index92).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index92[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index92[key];\n },\n });\n});\nvar _index93 = require(\"./getQuarter.cjs\");\nObject.keys(_index93).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index93[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index93[key];\n },\n });\n});\nvar _index94 = require(\"./getSeconds.cjs\");\nObject.keys(_index94).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index94[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index94[key];\n },\n });\n});\nvar _index95 = require(\"./getTime.cjs\");\nObject.keys(_index95).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index95[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index95[key];\n },\n });\n});\nvar _index96 = require(\"./getUnixTime.cjs\");\nObject.keys(_index96).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index96[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index96[key];\n },\n });\n});\nvar _index97 = require(\"./getWeek.cjs\");\nObject.keys(_index97).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index97[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index97[key];\n },\n });\n});\nvar _index98 = require(\"./getWeekOfMonth.cjs\");\nObject.keys(_index98).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index98[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index98[key];\n },\n });\n});\nvar _index99 = require(\"./getWeekYear.cjs\");\nObject.keys(_index99).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index99[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index99[key];\n },\n });\n});\nvar _index100 = require(\"./getWeeksInMonth.cjs\");\nObject.keys(_index100).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index100[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index100[key];\n },\n });\n});\nvar _index101 = require(\"./getYear.cjs\");\nObject.keys(_index101).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index101[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index101[key];\n },\n });\n});\nvar _index102 = require(\"./hoursToMilliseconds.cjs\");\nObject.keys(_index102).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index102[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index102[key];\n },\n });\n});\nvar _index103 = require(\"./hoursToMinutes.cjs\");\nObject.keys(_index103).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index103[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index103[key];\n },\n });\n});\nvar _index104 = require(\"./hoursToSeconds.cjs\");\nObject.keys(_index104).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index104[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index104[key];\n },\n });\n});\nvar _index105 = require(\"./interval.cjs\");\nObject.keys(_index105).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index105[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index105[key];\n },\n });\n});\nvar _index106 = require(\"./intervalToDuration.cjs\");\nObject.keys(_index106).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index106[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index106[key];\n },\n });\n});\nvar _index107 = require(\"./intlFormat.cjs\");\nObject.keys(_index107).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index107[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index107[key];\n },\n });\n});\nvar _index108 = require(\"./intlFormatDistance.cjs\");\nObject.keys(_index108).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index108[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index108[key];\n },\n });\n});\nvar _index109 = require(\"./isAfter.cjs\");\nObject.keys(_index109).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index109[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index109[key];\n },\n });\n});\nvar _index110 = require(\"./isBefore.cjs\");\nObject.keys(_index110).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index110[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index110[key];\n },\n });\n});\nvar _index111 = require(\"./isDate.cjs\");\nObject.keys(_index111).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index111[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index111[key];\n },\n });\n});\nvar _index112 = require(\"./isEqual.cjs\");\nObject.keys(_index112).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index112[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index112[key];\n },\n });\n});\nvar _index113 = require(\"./isExists.cjs\");\nObject.keys(_index113).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index113[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index113[key];\n },\n });\n});\nvar _index114 = require(\"./isFirstDayOfMonth.cjs\");\nObject.keys(_index114).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index114[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index114[key];\n },\n });\n});\nvar _index115 = require(\"./isFriday.cjs\");\nObject.keys(_index115).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index115[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index115[key];\n },\n });\n});\nvar _index116 = require(\"./isFuture.cjs\");\nObject.keys(_index116).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index116[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index116[key];\n },\n });\n});\nvar _index117 = require(\"./isLastDayOfMonth.cjs\");\nObject.keys(_index117).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index117[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index117[key];\n },\n });\n});\nvar _index118 = require(\"./isLeapYear.cjs\");\nObject.keys(_index118).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index118[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index118[key];\n },\n });\n});\nvar _index119 = require(\"./isMatch.cjs\");\nObject.keys(_index119).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index119[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index119[key];\n },\n });\n});\nvar _index120 = require(\"./isMonday.cjs\");\nObject.keys(_index120).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index120[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index120[key];\n },\n });\n});\nvar _index121 = require(\"./isPast.cjs\");\nObject.keys(_index121).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index121[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index121[key];\n },\n });\n});\nvar _index122 = require(\"./isSameDay.cjs\");\nObject.keys(_index122).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index122[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index122[key];\n },\n });\n});\nvar _index123 = require(\"./isSameHour.cjs\");\nObject.keys(_index123).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index123[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index123[key];\n },\n });\n});\nvar _index124 = require(\"./isSameISOWeek.cjs\");\nObject.keys(_index124).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index124[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index124[key];\n },\n });\n});\nvar _index125 = require(\"./isSameISOWeekYear.cjs\");\nObject.keys(_index125).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index125[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index125[key];\n },\n });\n});\nvar _index126 = require(\"./isSameMinute.cjs\");\nObject.keys(_index126).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index126[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index126[key];\n },\n });\n});\nvar _index127 = require(\"./isSameMonth.cjs\");\nObject.keys(_index127).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index127[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index127[key];\n },\n });\n});\nvar _index128 = require(\"./isSameQuarter.cjs\");\nObject.keys(_index128).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index128[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index128[key];\n },\n });\n});\nvar _index129 = require(\"./isSameSecond.cjs\");\nObject.keys(_index129).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index129[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index129[key];\n },\n });\n});\nvar _index130 = require(\"./isSameWeek.cjs\");\nObject.keys(_index130).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index130[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index130[key];\n },\n });\n});\nvar _index131 = require(\"./isSameYear.cjs\");\nObject.keys(_index131).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index131[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index131[key];\n },\n });\n});\nvar _index132 = require(\"./isSaturday.cjs\");\nObject.keys(_index132).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index132[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index132[key];\n },\n });\n});\nvar _index133 = require(\"./isSunday.cjs\");\nObject.keys(_index133).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index133[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index133[key];\n },\n });\n});\nvar _index134 = require(\"./isThisHour.cjs\");\nObject.keys(_index134).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index134[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index134[key];\n },\n });\n});\nvar _index135 = require(\"./isThisISOWeek.cjs\");\nObject.keys(_index135).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index135[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index135[key];\n },\n });\n});\nvar _index136 = require(\"./isThisMinute.cjs\");\nObject.keys(_index136).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index136[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index136[key];\n },\n });\n});\nvar _index137 = require(\"./isThisMonth.cjs\");\nObject.keys(_index137).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index137[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index137[key];\n },\n });\n});\nvar _index138 = require(\"./isThisQuarter.cjs\");\nObject.keys(_index138).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index138[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index138[key];\n },\n });\n});\nvar _index139 = require(\"./isThisSecond.cjs\");\nObject.keys(_index139).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index139[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index139[key];\n },\n });\n});\nvar _index140 = require(\"./isThisWeek.cjs\");\nObject.keys(_index140).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index140[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index140[key];\n },\n });\n});\nvar _index141 = require(\"./isThisYear.cjs\");\nObject.keys(_index141).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index141[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index141[key];\n },\n });\n});\nvar _index142 = require(\"./isThursday.cjs\");\nObject.keys(_index142).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index142[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index142[key];\n },\n });\n});\nvar _index143 = require(\"./isToday.cjs\");\nObject.keys(_index143).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index143[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index143[key];\n },\n });\n});\nvar _index144 = require(\"./isTomorrow.cjs\");\nObject.keys(_index144).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index144[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index144[key];\n },\n });\n});\nvar _index145 = require(\"./isTuesday.cjs\");\nObject.keys(_index145).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index145[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index145[key];\n },\n });\n});\nvar _index146 = require(\"./isValid.cjs\");\nObject.keys(_index146).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index146[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index146[key];\n },\n });\n});\nvar _index147 = require(\"./isWednesday.cjs\");\nObject.keys(_index147).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index147[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index147[key];\n },\n });\n});\nvar _index148 = require(\"./isWeekend.cjs\");\nObject.keys(_index148).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index148[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index148[key];\n },\n });\n});\nvar _index149 = require(\"./isWithinInterval.cjs\");\nObject.keys(_index149).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index149[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index149[key];\n },\n });\n});\nvar _index150 = require(\"./isYesterday.cjs\");\nObject.keys(_index150).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index150[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index150[key];\n },\n });\n});\nvar _index151 = require(\"./lastDayOfDecade.cjs\");\nObject.keys(_index151).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index151[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index151[key];\n },\n });\n});\nvar _index152 = require(\"./lastDayOfISOWeek.cjs\");\nObject.keys(_index152).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index152[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index152[key];\n },\n });\n});\nvar _index153 = require(\"./lastDayOfISOWeekYear.cjs\");\nObject.keys(_index153).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index153[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index153[key];\n },\n });\n});\nvar _index154 = require(\"./lastDayOfMonth.cjs\");\nObject.keys(_index154).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index154[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index154[key];\n },\n });\n});\nvar _index155 = require(\"./lastDayOfQuarter.cjs\");\nObject.keys(_index155).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index155[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index155[key];\n },\n });\n});\nvar _index156 = require(\"./lastDayOfWeek.cjs\");\nObject.keys(_index156).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index156[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index156[key];\n },\n });\n});\nvar _index157 = require(\"./lastDayOfYear.cjs\");\nObject.keys(_index157).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index157[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index157[key];\n },\n });\n});\nvar _index158 = require(\"./lightFormat.cjs\");\nObject.keys(_index158).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index158[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index158[key];\n },\n });\n});\nvar _index159 = require(\"./max.cjs\");\nObject.keys(_index159).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index159[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index159[key];\n },\n });\n});\nvar _index160 = require(\"./milliseconds.cjs\");\nObject.keys(_index160).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index160[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index160[key];\n },\n });\n});\nvar _index161 = require(\"./millisecondsToHours.cjs\");\nObject.keys(_index161).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index161[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index161[key];\n },\n });\n});\nvar _index162 = require(\"./millisecondsToMinutes.cjs\");\nObject.keys(_index162).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index162[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index162[key];\n },\n });\n});\nvar _index163 = require(\"./millisecondsToSeconds.cjs\");\nObject.keys(_index163).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index163[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index163[key];\n },\n });\n});\nvar _index164 = require(\"./min.cjs\");\nObject.keys(_index164).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index164[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index164[key];\n },\n });\n});\nvar _index165 = require(\"./minutesToHours.cjs\");\nObject.keys(_index165).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index165[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index165[key];\n },\n });\n});\nvar _index166 = require(\"./minutesToMilliseconds.cjs\");\nObject.keys(_index166).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index166[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index166[key];\n },\n });\n});\nvar _index167 = require(\"./minutesToSeconds.cjs\");\nObject.keys(_index167).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index167[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index167[key];\n },\n });\n});\nvar _index168 = require(\"./monthsToQuarters.cjs\");\nObject.keys(_index168).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index168[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index168[key];\n },\n });\n});\nvar _index169 = require(\"./monthsToYears.cjs\");\nObject.keys(_index169).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index169[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index169[key];\n },\n });\n});\nvar _index170 = require(\"./nextDay.cjs\");\nObject.keys(_index170).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index170[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index170[key];\n },\n });\n});\nvar _index171 = require(\"./nextFriday.cjs\");\nObject.keys(_index171).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index171[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index171[key];\n },\n });\n});\nvar _index172 = require(\"./nextMonday.cjs\");\nObject.keys(_index172).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index172[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index172[key];\n },\n });\n});\nvar _index173 = require(\"./nextSaturday.cjs\");\nObject.keys(_index173).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index173[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index173[key];\n },\n });\n});\nvar _index174 = require(\"./nextSunday.cjs\");\nObject.keys(_index174).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index174[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index174[key];\n },\n });\n});\nvar _index175 = require(\"./nextThursday.cjs\");\nObject.keys(_index175).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index175[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index175[key];\n },\n });\n});\nvar _index176 = require(\"./nextTuesday.cjs\");\nObject.keys(_index176).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index176[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index176[key];\n },\n });\n});\nvar _index177 = require(\"./nextWednesday.cjs\");\nObject.keys(_index177).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index177[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index177[key];\n },\n });\n});\nvar _index178 = require(\"./parse.cjs\");\nObject.keys(_index178).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index178[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index178[key];\n },\n });\n});\nvar _index179 = require(\"./parseISO.cjs\");\nObject.keys(_index179).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index179[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index179[key];\n },\n });\n});\nvar _index180 = require(\"./parseJSON.cjs\");\nObject.keys(_index180).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index180[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index180[key];\n },\n });\n});\nvar _index181 = require(\"./previousDay.cjs\");\nObject.keys(_index181).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index181[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index181[key];\n },\n });\n});\nvar _index182 = require(\"./previousFriday.cjs\");\nObject.keys(_index182).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index182[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index182[key];\n },\n });\n});\nvar _index183 = require(\"./previousMonday.cjs\");\nObject.keys(_index183).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index183[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index183[key];\n },\n });\n});\nvar _index184 = require(\"./previousSaturday.cjs\");\nObject.keys(_index184).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index184[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index184[key];\n },\n });\n});\nvar _index185 = require(\"./previousSunday.cjs\");\nObject.keys(_index185).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index185[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index185[key];\n },\n });\n});\nvar _index186 = require(\"./previousThursday.cjs\");\nObject.keys(_index186).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index186[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index186[key];\n },\n });\n});\nvar _index187 = require(\"./previousTuesday.cjs\");\nObject.keys(_index187).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index187[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index187[key];\n },\n });\n});\nvar _index188 = require(\"./previousWednesday.cjs\");\nObject.keys(_index188).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index188[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index188[key];\n },\n });\n});\nvar _index189 = require(\"./quartersToMonths.cjs\");\nObject.keys(_index189).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index189[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index189[key];\n },\n });\n});\nvar _index190 = require(\"./quartersToYears.cjs\");\nObject.keys(_index190).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index190[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index190[key];\n },\n });\n});\nvar _index191 = require(\"./roundToNearestHours.cjs\");\nObject.keys(_index191).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index191[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index191[key];\n },\n });\n});\nvar _index192 = require(\"./roundToNearestMinutes.cjs\");\nObject.keys(_index192).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index192[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index192[key];\n },\n });\n});\nvar _index193 = require(\"./secondsToHours.cjs\");\nObject.keys(_index193).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index193[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index193[key];\n },\n });\n});\nvar _index194 = require(\"./secondsToMilliseconds.cjs\");\nObject.keys(_index194).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index194[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index194[key];\n },\n });\n});\nvar _index195 = require(\"./secondsToMinutes.cjs\");\nObject.keys(_index195).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index195[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index195[key];\n },\n });\n});\nvar _index196 = require(\"./set.cjs\");\nObject.keys(_index196).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index196[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index196[key];\n },\n });\n});\nvar _index197 = require(\"./setDate.cjs\");\nObject.keys(_index197).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index197[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index197[key];\n },\n });\n});\nvar _index198 = require(\"./setDay.cjs\");\nObject.keys(_index198).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index198[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index198[key];\n },\n });\n});\nvar _index199 = require(\"./setDayOfYear.cjs\");\nObject.keys(_index199).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index199[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index199[key];\n },\n });\n});\nvar _index200 = require(\"./setDefaultOptions.cjs\");\nObject.keys(_index200).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index200[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index200[key];\n },\n });\n});\nvar _index201 = require(\"./setHours.cjs\");\nObject.keys(_index201).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index201[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index201[key];\n },\n });\n});\nvar _index202 = require(\"./setISODay.cjs\");\nObject.keys(_index202).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index202[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index202[key];\n },\n });\n});\nvar _index203 = require(\"./setISOWeek.cjs\");\nObject.keys(_index203).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index203[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index203[key];\n },\n });\n});\nvar _index204 = require(\"./setISOWeekYear.cjs\");\nObject.keys(_index204).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index204[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index204[key];\n },\n });\n});\nvar _index205 = require(\"./setMilliseconds.cjs\");\nObject.keys(_index205).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index205[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index205[key];\n },\n });\n});\nvar _index206 = require(\"./setMinutes.cjs\");\nObject.keys(_index206).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index206[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index206[key];\n },\n });\n});\nvar _index207 = require(\"./setMonth.cjs\");\nObject.keys(_index207).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index207[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index207[key];\n },\n });\n});\nvar _index208 = require(\"./setQuarter.cjs\");\nObject.keys(_index208).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index208[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index208[key];\n },\n });\n});\nvar _index209 = require(\"./setSeconds.cjs\");\nObject.keys(_index209).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index209[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index209[key];\n },\n });\n});\nvar _index210 = require(\"./setWeek.cjs\");\nObject.keys(_index210).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index210[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index210[key];\n },\n });\n});\nvar _index211 = require(\"./setWeekYear.cjs\");\nObject.keys(_index211).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index211[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index211[key];\n },\n });\n});\nvar _index212 = require(\"./setYear.cjs\");\nObject.keys(_index212).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index212[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index212[key];\n },\n });\n});\nvar _index213 = require(\"./startOfDay.cjs\");\nObject.keys(_index213).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index213[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index213[key];\n },\n });\n});\nvar _index214 = require(\"./startOfDecade.cjs\");\nObject.keys(_index214).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index214[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index214[key];\n },\n });\n});\nvar _index215 = require(\"./startOfHour.cjs\");\nObject.keys(_index215).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index215[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index215[key];\n },\n });\n});\nvar _index216 = require(\"./startOfISOWeek.cjs\");\nObject.keys(_index216).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index216[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index216[key];\n },\n });\n});\nvar _index217 = require(\"./startOfISOWeekYear.cjs\");\nObject.keys(_index217).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index217[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index217[key];\n },\n });\n});\nvar _index218 = require(\"./startOfMinute.cjs\");\nObject.keys(_index218).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index218[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index218[key];\n },\n });\n});\nvar _index219 = require(\"./startOfMonth.cjs\");\nObject.keys(_index219).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index219[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index219[key];\n },\n });\n});\nvar _index220 = require(\"./startOfQuarter.cjs\");\nObject.keys(_index220).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index220[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index220[key];\n },\n });\n});\nvar _index221 = require(\"./startOfSecond.cjs\");\nObject.keys(_index221).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index221[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index221[key];\n },\n });\n});\nvar _index222 = require(\"./startOfToday.cjs\");\nObject.keys(_index222).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index222[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index222[key];\n },\n });\n});\nvar _index223 = require(\"./startOfTomorrow.cjs\");\nObject.keys(_index223).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index223[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index223[key];\n },\n });\n});\nvar _index224 = require(\"./startOfWeek.cjs\");\nObject.keys(_index224).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index224[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index224[key];\n },\n });\n});\nvar _index225 = require(\"./startOfWeekYear.cjs\");\nObject.keys(_index225).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index225[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index225[key];\n },\n });\n});\nvar _index226 = require(\"./startOfYear.cjs\");\nObject.keys(_index226).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index226[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index226[key];\n },\n });\n});\nvar _index227 = require(\"./startOfYesterday.cjs\");\nObject.keys(_index227).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index227[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index227[key];\n },\n });\n});\nvar _index228 = require(\"./sub.cjs\");\nObject.keys(_index228).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index228[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index228[key];\n },\n });\n});\nvar _index229 = require(\"./subBusinessDays.cjs\");\nObject.keys(_index229).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index229[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index229[key];\n },\n });\n});\nvar _index230 = require(\"./subDays.cjs\");\nObject.keys(_index230).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index230[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index230[key];\n },\n });\n});\nvar _index231 = require(\"./subHours.cjs\");\nObject.keys(_index231).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index231[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index231[key];\n },\n });\n});\nvar _index232 = require(\"./subISOWeekYears.cjs\");\nObject.keys(_index232).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index232[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index232[key];\n },\n });\n});\nvar _index233 = require(\"./subMilliseconds.cjs\");\nObject.keys(_index233).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index233[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index233[key];\n },\n });\n});\nvar _index234 = require(\"./subMinutes.cjs\");\nObject.keys(_index234).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index234[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index234[key];\n },\n });\n});\nvar _index235 = require(\"./subMonths.cjs\");\nObject.keys(_index235).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index235[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index235[key];\n },\n });\n});\nvar _index236 = require(\"./subQuarters.cjs\");\nObject.keys(_index236).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index236[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index236[key];\n },\n });\n});\nvar _index237 = require(\"./subSeconds.cjs\");\nObject.keys(_index237).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index237[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index237[key];\n },\n });\n});\nvar _index238 = require(\"./subWeeks.cjs\");\nObject.keys(_index238).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index238[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index238[key];\n },\n });\n});\nvar _index239 = require(\"./subYears.cjs\");\nObject.keys(_index239).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index239[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index239[key];\n },\n });\n});\nvar _index240 = require(\"./toDate.cjs\");\nObject.keys(_index240).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index240[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index240[key];\n },\n });\n});\nvar _index241 = require(\"./transpose.cjs\");\nObject.keys(_index241).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index241[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index241[key];\n },\n });\n});\nvar _index242 = require(\"./weeksToDays.cjs\");\nObject.keys(_index242).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index242[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index242[key];\n },\n });\n});\nvar _index243 = require(\"./yearsToDays.cjs\");\nObject.keys(_index243).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index243[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index243[key];\n },\n });\n});\nvar _index244 = require(\"./yearsToMonths.cjs\");\nObject.keys(_index244).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index244[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index244[key];\n },\n });\n});\nvar _index245 = require(\"./yearsToQuarters.cjs\");\nObject.keys(_index245).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index245[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index245[key];\n },\n });\n});\n", "'use strict'\n\nconst { readdir, stat, unlink, symlink, lstat, readlink } = require('fs/promises')\nconst { dirname, join } = require('path')\nconst { format, addDays, addHours, parse, isValid } = require('date-fns')\n\nfunction parseSize (size) {\n let multiplier = 1024 ** 2\n if (typeof size !== 'string' && typeof size !== 'number') {\n return null\n }\n if (typeof size === 'string') {\n const match = size.match(/^([\\d.]+)(\\w?)$/)\n if (match) {\n const unit = match[2]?.toLowerCase()\n size = +match[1]\n multiplier = unit === 'g' ? 1024 ** 3 : unit === 'k' ? 1024 : unit === 'b' ? 1 : 1024 ** 2\n } else {\n throw new Error(`${size} is not a valid size in KB, MB or GB`)\n }\n }\n return size * multiplier\n}\n\nfunction parseFrequency (frequency) {\n const today = new Date()\n if (frequency === 'daily') {\n const start = today.setHours(0, 0, 0, 0)\n return { frequency, start, next: getNextDay(start) }\n }\n if (frequency === 'hourly') {\n const start = today.setMinutes(0, 0, 0)\n return { frequency, start, next: getNextHour(start) }\n }\n if (typeof frequency === 'number') {\n const start = today.getTime() - today.getTime() % frequency\n return { frequency, start, next: getNextCustom(frequency) }\n }\n if (frequency) {\n throw new Error(`${frequency} is neither a supported frequency or a number of milliseconds`)\n }\n return null\n}\n\nfunction validateLimitOptions (limit) {\n if (limit) {\n if (typeof limit !== 'object') {\n throw new Error('limit must be an object')\n }\n if (typeof limit.count !== 'number' || limit.count <= 0) {\n throw new Error('limit.count must be a number greater than 0')\n }\n if (typeof limit.removeOtherLogFiles !== 'undefined' && typeof limit.removeOtherLogFiles !== 'boolean') {\n throw new Error('limit.removeOtherLogFiles must be boolean')\n }\n }\n}\n\nfunction getNextDay (start) {\n return addDays(new Date(start), 1).setHours(0, 0, 0, 0)\n}\n\nfunction getNextHour (start) {\n return addHours(new Date(start), 1).setMinutes(0, 0, 0)\n}\n\nfunction getNextCustom (frequency) {\n const time = Date.now()\n return time - time % frequency + frequency\n}\n\nfunction getNext (frequency) {\n if (frequency === 'daily') {\n return getNextDay(new Date().setHours(0, 0, 0, 0))\n }\n if (frequency === 'hourly') {\n return getNextHour(new Date().setMinutes(0, 0, 0))\n }\n return getNextCustom(frequency)\n}\n\nfunction getFileName (fileVal) {\n if (!fileVal) {\n throw new Error('No file name provided')\n }\n return typeof fileVal === 'function' ? fileVal() : fileVal\n}\n\nfunction buildFileName (fileVal, date, lastNumber = 1, extension) {\n const dateStr = date ? `.${date}` : ''\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension : `.${extension}`\n return `${getFileName(fileVal)}${dateStr}.${lastNumber}${extensionStr}`\n}\n\nfunction identifyLogFile (checkedFileName, fileVal, dateFormat, extension) {\n const baseFileNameStr = getFileName(fileVal)\n if (!checkedFileName.startsWith(baseFileNameStr)) return false\n const checkFileNameSegments = checkedFileName\n .slice(baseFileNameStr.length + 1)\n .split('.')\n let expectedSegmentCount = 1\n if (typeof dateFormat === 'string' && dateFormat.length > 0) expectedSegmentCount++\n if (typeof extension === 'string' && extension.length > 0) expectedSegmentCount++\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension.slice(1) : extension\n if (checkFileNameSegments.length !== expectedSegmentCount) return false\n if (extensionStr.length > 0) {\n const chkExtension = checkFileNameSegments.pop()\n if (extensionStr !== chkExtension) return false\n }\n const chkFileNumber = checkFileNameSegments.pop()\n const fileNumber = Number(chkFileNumber)\n if (!Number.isInteger(fileNumber)) {\n return false\n }\n let fileTime = 0\n if (typeof dateFormat === 'string' && dateFormat.length > 0) {\n const d = parse(checkFileNameSegments[0], dateFormat, new Date())\n if (!isValid(d)) return false\n fileTime = d.getTime()\n }\n return { fileName: checkedFileName, fileTime, fileNumber }\n}\n\nasync function getFileSize (filePath) {\n try {\n const fileStats = await stat(filePath)\n return fileStats.size\n } catch {\n return 0\n }\n}\n\nasync function detectLastNumber (fileVal, time = null) {\n const fileName = getFileName(fileVal)\n try {\n const numbers = await readFileTrailingNumbers(dirname(fileName), time)\n return numbers.sort((a, b) => b - a)[0]\n } catch {\n return 1\n }\n}\n\nasync function readFileTrailingNumbers (folder, time) {\n const numbers = [1]\n for (const file of await readdir(folder)) {\n if (time && !(await isMatchingTime(join(folder, file), time))) {\n continue\n }\n const number = extractTrailingNumber(file)\n if (number) {\n numbers.push(number)\n }\n }\n return numbers\n}\n\nfunction extractTrailingNumber (fileName) {\n const match = fileName.match(/(\\d+)$/)\n return match ? +match[1] : null\n}\n\nfunction extractFileName (fileName) {\n return fileName.split(/(\\\\|\\/)/g).pop()\n}\n\nasync function isMatchingTime (filePath, time) {\n const { birthtimeMs } = await stat(filePath)\n return birthtimeMs >= time\n}\n\nasync function removeOldFiles ({ count, removeOtherLogFiles, baseFile, dateFormat, extension, createdFileNames, newFileName }) {\n if (!removeOtherLogFiles) {\n createdFileNames.push(newFileName)\n if (createdFileNames.length > count) {\n const filesToRemove = createdFileNames.splice(0, createdFileNames.length - 1 - count)\n await Promise.allSettled(filesToRemove.map(file => unlink(file)))\n }\n } else {\n let files = []\n const pathSegments = getFileName(baseFile).split(/(\\\\|\\/)/g)\n const baseFileNameStr = pathSegments.pop()\n for (const fileEntry of await readdir(join(...pathSegments))) {\n const f = identifyLogFile(fileEntry, baseFileNameStr, dateFormat, extension)\n if (f) {\n files.push(f)\n }\n }\n files = files.sort((i, j) => {\n if (i.fileTime === j.fileTime) {\n return i.fileNumber - j.fileNumber\n }\n return i.fileTime - j.fileTime\n })\n if (files.length > count) {\n await Promise.allSettled(\n files\n .slice(0, files.length - count)\n .map(file => unlink(join(...pathSegments, file.fileName)))\n )\n }\n }\n}\n\nasync function checkSymlink (fileName, linkPath) {\n const stats = await lstat(linkPath).then(stats => stats, () => null)\n if (stats?.isSymbolicLink()) {\n const existingTarget = await readlink(linkPath)\n if (extractFileName(existingTarget) === extractFileName(fileName)) {\n return false\n }\n await unlink(linkPath)\n }\n return true\n}\n\nasync function createSymlink (fileVal) {\n const linkPath = join(dirname(fileVal), 'current.log')\n const shouldCreateSymlink = await checkSymlink(fileVal, linkPath)\n if (shouldCreateSymlink) {\n await symlink(extractFileName(fileVal), linkPath)\n }\n return false\n}\n\nfunction validateDateFormat (formatStr) {\n const invalidChars = /[/\\\\?%*:|\"<>]/g\n if (invalidChars.test(formatStr)) {\n throw new Error(`${formatStr} contains invalid characters`)\n }\n return true\n}\n\nfunction parseDate (formatStr, frequencySpec, parseStart = false) {\n if (!(formatStr && frequencySpec?.start && frequencySpec.next)) return null\n\n try {\n return format(parseStart ? frequencySpec.start : frequencySpec.next, formatStr)\n } catch (error) {\n throw new Error(`${formatStr} must be a valid date format`)\n }\n}\n\nmodule.exports = {\n buildFileName,\n identifyLogFile,\n removeOldFiles,\n checkSymlink,\n createSymlink,\n detectLastNumber,\n extractFileName,\n parseFrequency,\n getNext,\n parseSize,\n getFileName,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n}\n", "'use strict'\n\nconst SonicBoom = require('sonic-boom')\nconst {\n buildFileName,\n removeOldFiles,\n createSymlink,\n detectLastNumber,\n parseSize,\n parseFrequency,\n getNext,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n} = require('./lib/utils')\n\n/**\n * A function that returns a string path to the base file name\n *\n * @typedef {function} LogFilePath\n * @returns {string}\n */\n\n/**\n * @typedef {object} Options\n *\n * @property {string|LogFilePath} file - Absolute or relative path to the log file.\n * Your application needs the write right on the parent folder.\n * Number will be appended to this file name.\n * When the parent folder already contains numbered files, numbering will continue based on the highest number.\n * If this path does not exist, the logger with throw an error unless you set `mkdir` to `true`.\n *\n * @property {string|number} size? - When specified, the maximum size of a given log file.\n * Can be combined with frequency.\n * Use 'k', 'm' and 'g' to express values in KB, MB or GB.\n * Numerical values will be considered as MB.\n *\n * @property {string|number} frequency? - When specified, the amount of time a given log file is used.\n * Can be combined with size.\n * Use 'daily' or 'hourly' to rotate file every day (or every hour).\n * Existing file within the current day (or hour) will be re-used.\n * Numerical values will be considered as a number of milliseconds.\n * Using a numerical value will always create a new file upon startup.\n *\n * @property {string} extension? - When specified, appends a file extension after the file number.\n *\n * @property {boolean} symlink? - When specified, creates a symlink to the current log file.\n *\n * @property {LimitOptions} limit? - strategy used to remove oldest files when rotating them.\n *\n * @property {string} dateFormat? - When specified, appends the current date/time to the file name in the provided format.\n * Supports date formats from `date-fns` (see: https://date-fns.org/v4.1.0/docs/format), such as 'yyyy-MM-dd' and 'yyyy-MM-dd-hh'.\n */\n\n/**\n * @typedef {object} LimitOptions\n *\n * @property {number} count? -number of log files, **in addition to the currently used file**.\n * @property {boolean} removeOtherLogFiles? - when true, older file matching the log file format will also be removed.\n */\n\n/**\n * @typedef {Options & import('sonic-boom').SonicBoomOpts} PinoRollOptions\n */\n\n/**\n * Creates a Pino transport (a Sonic-boom stream) to writing into files.\n * Automatically rolls your files based on a given frequency, size, or both.\n *\n * @param {PinoRollOptions} options - to configure file destionation, and rolling rules.\n * @returns {SonicBoom} the Sonic boom steam, usabled as Pino transport.\n */\nmodule.exports = async function ({\n file,\n size,\n frequency,\n extension,\n limit,\n symlink,\n dateFormat,\n ...opts\n} = {}) {\n validateLimitOptions(limit)\n validateDateFormat(dateFormat)\n const frequencySpec = parseFrequency(frequency)\n\n let date = parseDate(dateFormat, frequencySpec, true)\n let number = await detectLastNumber(file, frequencySpec?.start, dateFormat)\n\n let fileName = buildFileName(file, date, number, extension)\n const createdFileNames = [fileName]\n let currentSize = await getFileSize(fileName)\n const maxSize = parseSize(size)\n\n const destination = new SonicBoom({ ...opts, dest: fileName })\n\n if (symlink) {\n createSymlink(fileName)\n }\n\n let rollTimeout\n if (frequencySpec) {\n destination.once('close', () => {\n clearTimeout(rollTimeout)\n })\n scheduleRoll()\n }\n\n if (maxSize) {\n destination.on('write', writtenSize => {\n currentSize += writtenSize\n if (fileName === destination.file && currentSize >= maxSize) {\n currentSize = 0\n fileName = buildFileName(file, date, ++number, extension)\n // delay to let the destination finish its write\n destination.once('drain', roll)\n }\n })\n }\n\n function roll () {\n destination.reopen(fileName)\n if (symlink) {\n createSymlink(fileName)\n }\n if (limit) {\n removeOldFiles({ ...limit, baseFile: file, dateFormat, extension, createdFileNames, newFileName: fileName })\n }\n }\n\n function scheduleRoll () {\n clearTimeout(rollTimeout)\n rollTimeout = setTimeout(() => {\n const prevDate = date\n date = parseDate(dateFormat, frequencySpec)\n if (dateFormat && date && date !== prevDate) number = 0\n fileName = buildFileName(file, date, ++number, extension)\n roll()\n frequencySpec.next = getNext(frequency)\n scheduleRoll()\n }, frequencySpec.next - Date.now())\n }\n\n return destination\n}\n"], + "mappings": "wTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAIA,GAAI,OAAO,kBAAsB,KAAe,OAAO,QAAY,IAAa,CAG9E,IAASC,EAAT,SAAgBC,EAAI,CAGlB,IADcA,EAAK,GAAKA,EAAK,OACf,GACZ,MAAI,OAAOA,GAAO,UAAY,OAAOA,GAAO,SACpC,UAAU,4BAA4B,EAExC,WAAW,0EAA0E,EAG7F,QAAQ,KAAKC,EAAK,EAAG,EAAG,OAAOD,CAAE,CAAC,CACpC,EAbMC,EAAM,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,EAcnDH,GAAO,QAAUC,CACnB,KAAO,CAEL,IAASA,EAAT,SAAgBC,EAAI,CAGlB,IADcA,EAAK,GAAKA,EAAK,OACf,GACZ,MAAI,OAAOA,GAAO,UAAY,OAAOA,GAAO,SACpC,UAAU,4BAA4B,EAExC,WAAW,0EAA0E,EAE7F,IAAME,EAAS,KAAK,IAAI,EAAI,OAAOF,CAAE,EACrC,KAAOE,EAAS,KAAK,IAAI,GAAE,CAC7B,EAEAJ,GAAO,QAAUC,CAEnB,ICrC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,GAAcW,EAAMS,EAAMC,EAAQP,CAAS,EACpDS,EAAmB,CAACD,CAAQ,EAC9BE,EAAc,MAAMjB,GAAYe,CAAQ,EACtCG,EAAUrB,GAAUQ,CAAI,EAExBc,EAAc,IAAI3B,GAAU,CAAE,GAAGmB,EAAM,KAAMI,CAAS,CAAC,EAEzDN,GACFd,GAAcoB,CAAQ,EAGxB,IAAIK,EACAR,IACFO,EAAY,KAAK,QAAS,IAAM,CAC9B,aAAaC,CAAW,CAC1B,CAAC,EACDC,EAAa,GAGXH,GACFC,EAAY,GAAG,QAASG,GAAe,CACrCL,GAAeK,EACXP,IAAaI,EAAY,MAAQF,GAAeC,IAClDD,EAAc,EACdF,EAAWtB,GAAcW,EAAMS,EAAM,EAAEC,EAAQP,CAAS,EAExDY,EAAY,KAAK,QAASI,CAAI,EAElC,CAAC,EAGH,SAASA,GAAQ,CACfJ,EAAY,OAAOJ,CAAQ,EACvBN,GACFd,GAAcoB,CAAQ,EAEpBP,GACFd,GAAe,CAAE,GAAGc,EAAO,SAAUJ,EAAM,WAAAM,EAAY,UAAAH,EAAW,iBAAAS,EAAkB,YAAaD,CAAS,CAAC,CAE/G,CAEA,SAASM,GAAgB,CACvB,aAAaD,CAAW,EACxBA,EAAc,WAAW,IAAM,CAC7B,IAAMI,EAAWX,EACjBA,EAAOX,GAAUQ,EAAYE,CAAa,EACtCF,GAAcG,GAAQA,IAASW,IAAUV,EAAS,GACtDC,EAAWtB,GAAcW,EAAMS,EAAM,EAAEC,EAAQP,CAAS,EACxDgB,EAAK,EACLX,EAAc,KAAOb,GAAQO,CAAS,EACtCe,EAAa,CACf,EAAGT,EAAc,KAAO,KAAK,IAAI,CAAC,CACpC,CAEA,OAAOO,CACT", + "names": ["require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_constants", "__commonJSMin", "exports", "daysInWeek", "daysInYear", "maxTime", "minTime", "millisecondsInWeek", "millisecondsInDay", "millisecondsInMinute", "millisecondsInHour", "millisecondsInSecond", "minutesInYear", "minutesInMonth", "minutesInDay", "minutesInHour", "monthsInQuarter", "monthsInYear", "quartersInYear", "secondsInHour", "secondsInMinute", "secondsInDay", "secondsInWeek", "secondsInYear", "secondsInMonth", "secondsInQuarter", "constructFromSymbol", "require_constructFrom", "__commonJSMin", "exports", "constructFrom", "_index", "date", "value", "require_toDate", "__commonJSMin", "exports", "toDate", "_index", "argument", "context", "require_addDays", "__commonJSMin", "exports", "addDays", "_index", "_index2", "date", "amount", "options", "_date", "require_addMonths", "__commonJSMin", "exports", "addMonths", "_index", "_index2", "date", "amount", "options", "_date", "dayOfMonth", "endOfDesiredMonth", "daysInMonth", "require_add", "__commonJSMin", "exports", "add", "_index", "_index2", "_index3", "_index4", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "_date", "dateWithMonths", "dateWithDays", "minutesToAdd", "msToAdd", "require_isSaturday", "__commonJSMin", "exports", "isSaturday", "_index", "date", "options", "require_isSunday", "__commonJSMin", "exports", "isSunday", "_index", "date", "options", "require_isWeekend", "__commonJSMin", "exports", "isWeekend", "_index", "date", "options", "day", "require_addBusinessDays", "__commonJSMin", "exports", "addBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "date", "amount", "options", "_date", "startedOnWeekend", "hours", "sign", "fullWeeks", "restDays", "require_addMilliseconds", "__commonJSMin", "exports", "addMilliseconds", "_index", "_index2", "date", "amount", "options", "require_addHours", "__commonJSMin", "exports", "addHours", "_index", "_index2", "date", "amount", "options", "require_defaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "setDefaultOptions", "defaultOptions", "newOptions", "require_startOfWeek", "__commonJSMin", "exports", "startOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_startOfISOWeek", "__commonJSMin", "exports", "startOfISOWeek", "_index", "date", "options", "require_getISOWeekYear", "__commonJSMin", "exports", "getISOWeekYear", "_index", "_index2", "_index3", "date", "options", "_date", "year", "fourthOfJanuaryOfNextYear", "startOfNextYear", "fourthOfJanuaryOfThisYear", "startOfThisYear", "require_getTimezoneOffsetInMilliseconds", "__commonJSMin", "exports", "getTimezoneOffsetInMilliseconds", "_index", "date", "_date", "utcDate", "require_normalizeDates", "__commonJSMin", "exports", "normalizeDates", "_index", "context", "dates", "normalize", "date", "require_startOfDay", "__commonJSMin", "exports", "startOfDay", "_index", "date", "options", "_date", "require_differenceInCalendarDays", "__commonJSMin", "exports", "differenceInCalendarDays", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfDay", "earlierStartOfDay", "laterTimestamp", "earlierTimestamp", "require_startOfISOWeekYear", "__commonJSMin", "exports", "startOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "require_setISOWeekYear", "__commonJSMin", "exports", "setISOWeekYear", "_index", "_index2", "_index3", "_index4", "date", "weekYear", "options", "_date", "diff", "fourthOfJanuary", "require_addISOWeekYears", "__commonJSMin", "exports", "addISOWeekYears", "_index", "_index2", "date", "amount", "options", "require_addMinutes", "__commonJSMin", "exports", "addMinutes", "_index", "_index2", "date", "amount", "options", "_date", "require_addQuarters", "__commonJSMin", "exports", "addQuarters", "_index", "date", "amount", "options", "require_addSeconds", "__commonJSMin", "exports", "addSeconds", "_index", "date", "amount", "options", "require_addWeeks", "__commonJSMin", "exports", "addWeeks", "_index", "date", "amount", "options", "require_addYears", "__commonJSMin", "exports", "addYears", "_index", "date", "amount", "options", "require_areIntervalsOverlapping", "__commonJSMin", "exports", "areIntervalsOverlapping", "_index", "intervalLeft", "intervalRight", "options", "leftStartTime", "leftEndTime", "a", "b", "rightStartTime", "rightEndTime", "require_max", "__commonJSMin", "exports", "max", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_min", "__commonJSMin", "exports", "min", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_clamp", "__commonJSMin", "exports", "clamp", "_index", "_index2", "_index3", "date", "interval", "options", "date_", "start", "end", "require_closestIndexTo", "__commonJSMin", "exports", "closestIndexTo", "_index", "dateToCompare", "dates", "timeToCompare", "result", "minDistance", "date", "index", "date_", "distance", "require_closestTo", "__commonJSMin", "exports", "closestTo", "_index", "_index2", "_index3", "dateToCompare", "dates", "options", "dateToCompare_", "dates_", "index", "require_compareAsc", "__commonJSMin", "exports", "compareAsc", "_index", "dateLeft", "dateRight", "diff", "require_compareDesc", "__commonJSMin", "exports", "compareDesc", "_index", "dateLeft", "dateRight", "diff", "require_constructNow", "__commonJSMin", "exports", "constructNow", "_index", "date", "require_daysToWeeks", "__commonJSMin", "exports", "daysToWeeks", "_index", "days", "result", "require_isSameDay", "__commonJSMin", "exports", "isSameDay", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_isDate", "__commonJSMin", "exports", "isDate", "value", "require_isValid", "__commonJSMin", "exports", "isValid", "_index", "_index2", "date", "require_differenceInBusinessDays", "__commonJSMin", "exports", "differenceInBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "sign", "weeks", "result", "movingDate", "require_differenceInCalendarISOWeekYears", "__commonJSMin", "exports", "differenceInCalendarISOWeekYears", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInCalendarISOWeeks", "__commonJSMin", "exports", "differenceInCalendarISOWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "startOfISOWeekLeft", "startOfISOWeekRight", "timestampLeft", "timestampRight", "require_differenceInCalendarMonths", "__commonJSMin", "exports", "differenceInCalendarMonths", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "monthsDiff", "require_getQuarter", "__commonJSMin", "exports", "getQuarter", "_index", "date", "options", "_date", "require_differenceInCalendarQuarters", "__commonJSMin", "exports", "differenceInCalendarQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "quartersDiff", "require_differenceInCalendarWeeks", "__commonJSMin", "exports", "differenceInCalendarWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfWeek", "earlierStartOfWeek", "laterTimestamp", "earlierTimestamp", "require_differenceInCalendarYears", "__commonJSMin", "exports", "differenceInCalendarYears", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInDays", "__commonJSMin", "exports", "differenceInDays", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "compareLocalAsc", "difference", "isLastDayNotFull", "result", "diff", "require_getRoundingMethod", "__commonJSMin", "exports", "getRoundingMethod", "method", "number", "result", "require_differenceInHours", "__commonJSMin", "exports", "differenceInHours", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "require_subISOWeekYears", "__commonJSMin", "exports", "subISOWeekYears", "_index", "date", "amount", "options", "require_differenceInISOWeekYears", "__commonJSMin", "exports", "differenceInISOWeekYears", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "adjustedDate", "isLastISOWeekYearNotFull", "result", "require_differenceInMilliseconds", "__commonJSMin", "exports", "differenceInMilliseconds", "_index", "laterDate", "earlierDate", "require_differenceInMinutes", "__commonJSMin", "exports", "differenceInMinutes", "_index", "_index2", "_index3", "dateLeft", "dateRight", "options", "diff", "require_endOfDay", "__commonJSMin", "exports", "endOfDay", "_index", "date", "options", "_date", "require_endOfMonth", "__commonJSMin", "exports", "endOfMonth", "_index", "date", "options", "_date", "month", "require_isLastDayOfMonth", "__commonJSMin", "exports", "isLastDayOfMonth", "_index", "_index2", "_index3", "date", "options", "_date", "require_differenceInMonths", "__commonJSMin", "exports", "differenceInMonths", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "workingLaterDate", "earlierDate_", "sign", "difference", "isLastMonthNotFull", "result", "require_differenceInQuarters", "__commonJSMin", "exports", "differenceInQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInSeconds", "__commonJSMin", "exports", "differenceInSeconds", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInWeeks", "__commonJSMin", "exports", "differenceInWeeks", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInYears", "__commonJSMin", "exports", "differenceInYears", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "partial", "result", "require_normalizeInterval", "__commonJSMin", "exports", "normalizeInterval", "_index", "context", "interval", "start", "end", "require_eachDayOfInterval", "__commonJSMin", "exports", "eachDayOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachHourOfInterval", "__commonJSMin", "exports", "eachHourOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMinuteOfInterval", "__commonJSMin", "exports", "eachMinuteOfInterval", "_index", "_index2", "_index3", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMonthOfInterval", "__commonJSMin", "exports", "eachMonthOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_startOfQuarter", "__commonJSMin", "exports", "startOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_eachQuarterOfInterval", "__commonJSMin", "exports", "eachQuarterOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachWeekOfInterval", "__commonJSMin", "exports", "eachWeekOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "startDateWeek", "endDateWeek", "endTime", "currentDate", "step", "dates", "require_eachWeekendOfInterval", "__commonJSMin", "exports", "eachWeekendOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "dateInterval", "weekends", "index", "date", "require_startOfMonth", "__commonJSMin", "exports", "startOfMonth", "_index", "date", "options", "_date", "require_eachWeekendOfMonth", "__commonJSMin", "exports", "eachWeekendOfMonth", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_endOfYear", "__commonJSMin", "exports", "endOfYear", "_index", "date", "options", "_date", "year", "require_startOfYear", "__commonJSMin", "exports", "startOfYear", "_index", "date", "options", "date_", "require_eachWeekendOfYear", "__commonJSMin", "exports", "eachWeekendOfYear", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_eachYearOfInterval", "__commonJSMin", "exports", "eachYearOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_endOfDecade", "__commonJSMin", "exports", "endOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_endOfHour", "__commonJSMin", "exports", "endOfHour", "_index", "date", "options", "_date", "require_endOfWeek", "__commonJSMin", "exports", "endOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_endOfISOWeek", "__commonJSMin", "exports", "endOfISOWeek", "_index", "date", "options", "require_endOfISOWeekYear", "__commonJSMin", "exports", "endOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuaryOfNextYear", "_date", "require_endOfMinute", "__commonJSMin", "exports", "endOfMinute", "_index", "date", "options", "_date", "require_endOfQuarter", "__commonJSMin", "exports", "endOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_endOfSecond", "__commonJSMin", "exports", "endOfSecond", "_index", "date", "options", "_date", "require_endOfToday", "__commonJSMin", "exports", "endOfToday", "_index", "options", "require_endOfTomorrow", "__commonJSMin", "exports", "endOfTomorrow", "_index", "options", "now", "year", "month", "day", "date", "require_endOfYesterday", "__commonJSMin", "exports", "endOfYesterday", "_index", "_index2", "options", "now", "date", "require_formatDistance", "__commonJSMin", "exports", "formatDistanceLocale", "formatDistance", "token", "count", "options", "result", "tokenValue", "require_buildFormatLongFn", "__commonJSMin", "exports", "buildFormatLongFn", "args", "options", "width", "require_formatLong", "__commonJSMin", "exports", "_index", "dateFormats", "timeFormats", "dateTimeFormats", "formatLong", "require_formatRelative", "__commonJSMin", "exports", "formatRelativeLocale", "formatRelative", "token", "_date", "_baseDate", "_options", "require_buildLocalizeFn", "__commonJSMin", "exports", "buildLocalizeFn", "args", "value", "options", "context", "valuesArray", "defaultWidth", "width", "index", "require_localize", "__commonJSMin", "exports", "_index", "eraValues", "quarterValues", "monthValues", "dayValues", "dayPeriodValues", "formattingDayPeriodValues", "ordinalNumber", "dirtyNumber", "_options", "number", "rem100", "localize", "quarter", "require_buildMatchFn", "__commonJSMin", "exports", "buildMatchFn", "args", "string", "options", "width", "matchPattern", "matchResult", "matchedString", "parsePatterns", "key", "findIndex", "pattern", "findKey", "value", "rest", "object", "predicate", "array", "require_buildMatchPatternFn", "__commonJSMin", "exports", "buildMatchPatternFn", "args", "string", "options", "matchResult", "matchedString", "parseResult", "value", "rest", "require_match", "__commonJSMin", "exports", "_index", "_index2", "matchOrdinalNumberPattern", "parseOrdinalNumberPattern", "matchEraPatterns", "parseEraPatterns", "matchQuarterPatterns", "parseQuarterPatterns", "matchMonthPatterns", "parseMonthPatterns", "matchDayPatterns", "parseDayPatterns", "matchDayPeriodPatterns", "parseDayPeriodPatterns", "match", "value", "index", "require_en_US", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "enUS", "require_defaultLocale", "__commonJSMin", "exports", "_index", "require_getDayOfYear", "__commonJSMin", "exports", "getDayOfYear", "_index", "_index2", "_index3", "date", "options", "_date", "require_getISOWeek", "__commonJSMin", "exports", "getISOWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_getWeekYear", "__commonJSMin", "exports", "getWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "year", "defaultOptions", "firstWeekContainsDate", "firstWeekOfNextYear", "startOfNextYear", "firstWeekOfThisYear", "startOfThisYear", "require_startOfWeekYear", "__commonJSMin", "exports", "startOfWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "defaultOptions", "firstWeekContainsDate", "year", "firstWeek", "require_getWeek", "__commonJSMin", "exports", "getWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_addLeadingZeros", "__commonJSMin", "exports", "addLeadingZeros", "number", "targetLength", "sign", "output", "require_lightFormatters", "__commonJSMin", "exports", "_index", "lightFormatters", "date", "token", "signedYear", "year", "month", "dayPeriodEnumValue", "numberOfDigits", "milliseconds", "fractionalSeconds", "require_formatters", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "dayPeriodEnum", "formatters", "date", "token", "localize", "era", "signedYear", "year", "options", "signedWeekYear", "weekYear", "twoDigitYear", "isoWeekYear", "quarter", "month", "week", "isoWeek", "dayOfYear", "dayOfWeek", "localDayOfWeek", "isoDayOfWeek", "dayPeriodEnumValue", "hours", "_localize", "timezoneOffset", "formatTimezoneWithOptionalMinutes", "formatTimezone", "formatTimezoneShort", "timestamp", "offset", "delimiter", "sign", "absOffset", "minutes", "require_longFormatters", "__commonJSMin", "exports", "dateLongFormatter", "pattern", "formatLong", "timeLongFormatter", "dateTimeLongFormatter", "matchResult", "datePattern", "timePattern", "dateTimeFormat", "longFormatters", "require_protectedTokens", "__commonJSMin", "exports", "isProtectedDayOfYearToken", "isProtectedWeekYearToken", "warnOrThrowProtectedError", "dayOfYearTokenRE", "weekYearTokenRE", "throwTokens", "token", "format", "input", "_message", "message", "subject", "require_format", "__commonJSMin", "exports", "format", "_index3", "_index4", "_index", "_index2", "_index5", "_index6", "_index7", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "options", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "originalDate", "parts", "substring", "firstCharacter", "longFormatter", "cleanEscapedString", "formatterOptions", "part", "token", "formatter", "input", "matched", "require_formatDistance", "__commonJSMin", "exports", "formatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "minutesInAlmostTwoDays", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "seconds", "offsetInSeconds", "minutes", "months", "hours", "days", "nearestMonth", "monthsSinceStartOfYear", "years", "require_formatDistanceStrict", "__commonJSMin", "exports", "formatDistanceStrict", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "roundingMethod", "milliseconds", "minutes", "timezoneOffset", "dstNormalizedMinutes", "defaultUnit", "unit", "seconds", "roundedMinutes", "hours", "days", "months", "years", "require_formatDistanceToNow", "__commonJSMin", "exports", "formatDistanceToNow", "_index", "_index2", "date", "options", "require_formatDistanceToNowStrict", "__commonJSMin", "exports", "formatDistanceToNowStrict", "_index", "_index2", "date", "options", "require_formatDuration", "__commonJSMin", "exports", "formatDuration", "_index", "_index2", "defaultFormat", "duration", "options", "defaultOptions", "locale", "format", "zero", "delimiter", "acc", "unit", "token", "m", "value", "require_formatISO", "__commonJSMin", "exports", "formatISO", "_index", "_index2", "date", "options", "date_", "format", "representation", "result", "tzOffset", "dateDelimiter", "timeDelimiter", "day", "month", "offset", "absoluteOffset", "hourOffset", "minuteOffset", "hour", "minute", "second", "separator", "time", "require_formatISO9075", "__commonJSMin", "exports", "formatISO9075", "_index", "_index2", "_index3", "date", "options", "date_", "format", "representation", "result", "dateDelimiter", "timeDelimiter", "day", "month", "hour", "minute", "second", "require_formatISODuration", "__commonJSMin", "exports", "formatISODuration", "duration", "years", "months", "days", "hours", "minutes", "seconds", "require_formatRFC3339", "__commonJSMin", "exports", "formatRFC3339", "_index", "_index2", "_index3", "date", "options", "date_", "fractionDigits", "day", "month", "year", "hour", "minute", "second", "fractionalSecond", "milliseconds", "fractionalSeconds", "offset", "tzOffset", "absoluteOffset", "hourOffset", "minuteOffset", "require_formatRFC7231", "__commonJSMin", "exports", "formatRFC7231", "_index", "_index2", "_index3", "days", "months", "date", "_date", "dayName", "dayOfMonth", "monthName", "year", "hour", "minute", "second", "require_formatRelative", "__commonJSMin", "exports", "formatRelative", "_index", "_index2", "_index3", "_index4", "_index5", "date", "baseDate", "options", "date_", "baseDate_", "defaultOptions", "locale", "weekStartsOn", "diff", "token", "formatStr", "require_fromUnixTime", "__commonJSMin", "exports", "fromUnixTime", "_index", "unixTime", "options", "require_getDate", "__commonJSMin", "exports", "getDate", "_index", "date", "options", "require_getDay", "__commonJSMin", "exports", "getDay", "_index", "date", "options", "require_getDaysInMonth", "__commonJSMin", "exports", "getDaysInMonth", "_index", "_index2", "date", "options", "_date", "year", "monthIndex", "lastDayOfMonth", "require_isLeapYear", "__commonJSMin", "exports", "isLeapYear", "_index", "date", "options", "year", "require_getDaysInYear", "__commonJSMin", "exports", "getDaysInYear", "_index", "_index2", "date", "options", "_date", "require_getDecade", "__commonJSMin", "exports", "getDecade", "_index", "date", "options", "year", "require_getDefaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "_index", "require_getHours", "__commonJSMin", "exports", "getHours", "_index", "date", "options", "require_getISODay", "__commonJSMin", "exports", "getISODay", "_index", "date", "options", "day", "require_getISOWeeksInYear", "__commonJSMin", "exports", "getISOWeeksInYear", "_index", "_index2", "_index3", "date", "options", "thisYear", "diff", "require_getMilliseconds", "__commonJSMin", "exports", "getMilliseconds", "_index", "date", "require_getMinutes", "__commonJSMin", "exports", "getMinutes", "_index", "date", "options", "require_getMonth", "__commonJSMin", "exports", "getMonth", "_index", "date", "options", "require_getOverlappingDaysInIntervals", "__commonJSMin", "exports", "getOverlappingDaysInIntervals", "_index", "_index2", "_index3", "intervalLeft", "intervalRight", "leftStart", "leftEnd", "a", "b", "rightStart", "rightEnd", "overlapLeft", "left", "overlapRight", "right", "require_getSeconds", "__commonJSMin", "exports", "getSeconds", "_index", "date", "require_getTime", "__commonJSMin", "exports", "getTime", "_index", "date", "require_getUnixTime", "__commonJSMin", "exports", "getUnixTime", "_index", "date", "require_getWeekOfMonth", "__commonJSMin", "exports", "getWeekOfMonth", "_index", "_index2", "_index3", "_index4", "_index5", "date", "options", "defaultOptions", "weekStartsOn", "currentDayOfMonth", "startWeekDay", "lastDayOfFirstWeek", "remainingDaysAfterFirstWeek", "require_lastDayOfMonth", "__commonJSMin", "exports", "lastDayOfMonth", "_index", "date", "options", "_date", "month", "require_getWeeksInMonth", "__commonJSMin", "exports", "getWeeksInMonth", "_index", "_index2", "_index3", "_index4", "date", "options", "contextDate", "require_getYear", "__commonJSMin", "exports", "getYear", "_index", "date", "options", "require_hoursToMilliseconds", "__commonJSMin", "exports", "hoursToMilliseconds", "_index", "hours", "require_hoursToMinutes", "__commonJSMin", "exports", "hoursToMinutes", "_index", "hours", "require_hoursToSeconds", "__commonJSMin", "exports", "hoursToSeconds", "_index", "hours", "require_interval", "__commonJSMin", "exports", "interval", "_index", "start", "end", "options", "_start", "_end", "require_intervalToDuration", "__commonJSMin", "exports", "intervalToDuration", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "interval", "options", "start", "end", "duration", "years", "remainingMonths", "months", "remainingDays", "days", "remainingHours", "hours", "remainingMinutes", "minutes", "remainingSeconds", "seconds", "require_intlFormat", "__commonJSMin", "exports", "intlFormat", "_index", "date", "formatOrLocale", "localeOptions", "formatOptions", "isFormatOptions", "opts", "require_intlFormatDistance", "__commonJSMin", "exports", "intlFormatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "laterDate", "earlierDate", "options", "value", "unit", "laterDate_", "earlierDate_", "diffInSeconds", "require_isAfter", "__commonJSMin", "exports", "isAfter", "_index", "date", "dateToCompare", "require_isBefore", "__commonJSMin", "exports", "isBefore", "_index", "date", "dateToCompare", "require_isEqual", "__commonJSMin", "exports", "isEqual", "_index", "leftDate", "rightDate", "require_isExists", "__commonJSMin", "exports", "isExists", "year", "month", "day", "date", "require_isFirstDayOfMonth", "__commonJSMin", "exports", "isFirstDayOfMonth", "_index", "date", "options", "require_isFriday", "__commonJSMin", "exports", "isFriday", "_index", "date", "options", "require_isFuture", "__commonJSMin", "exports", "isFuture", "_index", "date", "require_transpose", "__commonJSMin", "exports", "transpose", "_index", "date", "constructor", "date_", "isConstructor", "require_Setter", "__commonJSMin", "exports", "_index", "_index2", "TIMEZONE_UNIT_PRIORITY", "Setter", "_utcDate", "_options", "ValueSetter", "value", "validateValue", "setValue", "priority", "subPriority", "date", "options", "flags", "DateTimezoneSetter", "context", "reference", "require_Parser", "__commonJSMin", "exports", "_Setter", "Parser", "dateString", "token", "match", "options", "result", "_utcDate", "_value", "_options", "require_EraParser", "__commonJSMin", "exports", "_Parser", "EraParser", "dateString", "token", "match", "date", "flags", "value", "require_constants", "__commonJSMin", "exports", "numericPatterns", "timezonePatterns", "require_utils", "__commonJSMin", "exports", "dayPeriodEnumToHours", "isLeapYearIndex", "mapValue", "normalizeTwoDigitYear", "parseAnyDigitsSigned", "parseNDigits", "parseNDigitsSigned", "parseNumericPattern", "parseTimezonePattern", "_index", "_constants", "parseFnResult", "mapFn", "pattern", "dateString", "matchResult", "sign", "hours", "minutes", "seconds", "n", "dayPeriod", "twoDigitYear", "currentYear", "isCommonEra", "absCurrentYear", "result", "rangeEnd", "rangeEndCentury", "isPreviousCentury", "year", "require_YearParser", "__commonJSMin", "exports", "_Parser", "_utils", "YearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "currentYear", "normalizedTwoDigitYear", "require_LocalWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "LocalWeekYearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "options", "currentYear", "normalizedTwoDigitYear", "require_ISOWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "ISOWeekYearParser", "dateString", "token", "date", "_flags", "value", "firstWeekOfYear", "require_ExtendedYearParser", "__commonJSMin", "exports", "_Parser", "_utils", "ExtendedYearParser", "dateString", "token", "date", "_flags", "value", "require_QuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "QuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_StandAloneQuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "StandAloneQuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_MonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_StandAloneMonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "StandAloneMonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_setWeek", "__commonJSMin", "exports", "setWeek", "_index", "_index2", "date", "week", "options", "date_", "diff", "require_LocalWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "LocalWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_setISOWeek", "__commonJSMin", "exports", "setISOWeek", "_index", "_index2", "date", "week", "options", "_date", "diff", "require_ISOWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_DateParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DAYS_IN_MONTH", "DAYS_IN_MONTH_LEAP_YEAR", "DateParser", "dateString", "token", "match", "date", "value", "year", "isLeapYear", "month", "_flags", "require_DayOfYearParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DayOfYearParser", "dateString", "token", "match", "date", "value", "year", "_flags", "require_setDay", "__commonJSMin", "exports", "setDay", "_index", "_index2", "_index3", "date", "day", "options", "defaultOptions", "weekStartsOn", "date_", "currentDay", "dayIndex", "delta", "diff", "require_DayParser", "__commonJSMin", "exports", "_index", "_Parser", "DayParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_LocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "LocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_StandAloneLocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "StandAloneLocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_setISODay", "__commonJSMin", "exports", "setISODay", "_index", "_index2", "_index3", "date", "day", "options", "date_", "currentDay", "diff", "require_ISODayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "ISODayParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_AMPMParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMParser", "dateString", "token", "match", "date", "_flags", "value", "require_AMPMMidnightParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMMidnightParser", "dateString", "token", "match", "date", "_flags", "value", "require_DayPeriodParser", "__commonJSMin", "exports", "_Parser", "_utils", "DayPeriodParser", "dateString", "token", "match", "date", "_flags", "value", "require_Hour1to12Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1to12Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "isPM", "require_Hour0to23Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0to23Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour0To11Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0To11Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour1To24Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1To24Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "hours", "require_MinuteParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MinuteParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_SecondParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "SecondParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_FractionOfSecondParser", "__commonJSMin", "exports", "_Parser", "_utils", "FractionOfSecondParser", "dateString", "token", "valueCallback", "value", "date", "_flags", "require_ISOTimezoneWithZParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneWithZParser", "dateString", "token", "date", "flags", "value", "require_ISOTimezoneParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneParser", "dateString", "token", "date", "flags", "value", "require_TimestampSecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampSecondsParser", "dateString", "date", "_flags", "value", "require_TimestampMillisecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampMillisecondsParser", "dateString", "date", "_flags", "value", "require_parsers", "__commonJSMin", "exports", "_EraParser", "_YearParser", "_LocalWeekYearParser", "_ISOWeekYearParser", "_ExtendedYearParser", "_QuarterParser", "_StandAloneQuarterParser", "_MonthParser", "_StandAloneMonthParser", "_LocalWeekParser", "_ISOWeekParser", "_DateParser", "_DayOfYearParser", "_DayParser", "_LocalDayParser", "_StandAloneLocalDayParser", "_ISODayParser", "_AMPMParser", "_AMPMMidnightParser", "_DayPeriodParser", "_Hour1to12Parser", "_Hour0to23Parser", "_Hour0To11Parser", "_Hour1To24Parser", "_MinuteParser", "_SecondParser", "_FractionOfSecondParser", "_ISOTimezoneWithZParser", "_ISOTimezoneParser", "_TimestampSecondsParser", "_TimestampMillisecondsParser", "parsers", "require_parse", "__commonJSMin", "exports", "_index2", "parse", "_index7", "_index", "_index3", "_index4", "_index5", "_index6", "_Setter", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "notWhitespaceRegExp", "unescapedLatinCharacterRegExp", "dateStr", "formatStr", "referenceDate", "options", "invalidDate", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "subFnOptions", "setters", "tokens", "substring", "firstCharacter", "longFormatter", "usedTokens", "token", "parser", "incompatibleTokens", "incompatibleToken", "usedToken", "parseResult", "cleanEscapedString", "uniquePrioritySetters", "setter", "a", "b", "priority", "index", "array", "setterArray", "date", "flags", "result", "input", "require_isMatch", "__commonJSMin", "exports", "isMatch", "_index", "_index2", "dateStr", "formatStr", "options", "require_isMonday", "__commonJSMin", "exports", "isMonday", "_index", "date", "options", "require_isPast", "__commonJSMin", "exports", "isPast", "_index", "date", "require_startOfHour", "__commonJSMin", "exports", "startOfHour", "_index", "date", "options", "_date", "require_isSameHour", "__commonJSMin", "exports", "isSameHour", "_index", "_index2", "dateLeft", "dateRight", "options", "dateLeft_", "dateRight_", "require_isSameWeek", "__commonJSMin", "exports", "isSameWeek", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameISOWeek", "__commonJSMin", "exports", "isSameISOWeek", "_index", "laterDate", "earlierDate", "options", "require_isSameISOWeekYear", "__commonJSMin", "exports", "isSameISOWeekYear", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_startOfMinute", "__commonJSMin", "exports", "startOfMinute", "_index", "date", "options", "date_", "require_isSameMinute", "__commonJSMin", "exports", "isSameMinute", "_index", "laterDate", "earlierDate", "require_isSameMonth", "__commonJSMin", "exports", "isSameMonth", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameQuarter", "__commonJSMin", "exports", "isSameQuarter", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_startOfSecond", "__commonJSMin", "exports", "startOfSecond", "_index", "date", "options", "date_", "require_isSameSecond", "__commonJSMin", "exports", "isSameSecond", "_index", "laterDate", "earlierDate", "require_isSameYear", "__commonJSMin", "exports", "isSameYear", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isThisHour", "__commonJSMin", "exports", "isThisHour", "_index", "_index2", "_index3", "date", "options", "require_isThisISOWeek", "__commonJSMin", "exports", "isThisISOWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisMinute", "__commonJSMin", "exports", "isThisMinute", "_index", "_index2", "date", "require_isThisMonth", "__commonJSMin", "exports", "isThisMonth", "_index", "_index2", "_index3", "date", "options", "require_isThisQuarter", "__commonJSMin", "exports", "isThisQuarter", "_index", "_index2", "_index3", "date", "options", "require_isThisSecond", "__commonJSMin", "exports", "isThisSecond", "_index", "_index2", "date", "require_isThisWeek", "__commonJSMin", "exports", "isThisWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisYear", "__commonJSMin", "exports", "isThisYear", "_index", "_index2", "_index3", "date", "options", "require_isThursday", "__commonJSMin", "exports", "isThursday", "_index", "date", "options", "require_isToday", "__commonJSMin", "exports", "isToday", "_index", "_index2", "_index3", "date", "options", "require_isTomorrow", "__commonJSMin", "exports", "isTomorrow", "_index", "_index2", "_index3", "date", "options", "require_isTuesday", "__commonJSMin", "exports", "isTuesday", "_index", "date", "options", "require_isWednesday", "__commonJSMin", "exports", "isWednesday", "_index", "date", "options", "require_isWithinInterval", "__commonJSMin", "exports", "isWithinInterval", "_index", "date", "interval", "options", "time", "startTime", "endTime", "a", "b", "require_subDays", "__commonJSMin", "exports", "subDays", "_index", "date", "amount", "options", "require_isYesterday", "__commonJSMin", "exports", "isYesterday", "_index", "_index2", "_index3", "_index4", "date", "options", "require_lastDayOfDecade", "__commonJSMin", "exports", "lastDayOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_lastDayOfWeek", "__commonJSMin", "exports", "lastDayOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_lastDayOfISOWeek", "__commonJSMin", "exports", "lastDayOfISOWeek", "_index", "date", "options", "require_lastDayOfISOWeekYear", "__commonJSMin", "exports", "lastDayOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "date_", "require_lastDayOfQuarter", "__commonJSMin", "exports", "lastDayOfQuarter", "_index", "date", "options", "date_", "currentMonth", "month", "require_lastDayOfYear", "__commonJSMin", "exports", "lastDayOfYear", "_index", "date", "options", "date_", "year", "require_lightFormat", "__commonJSMin", "exports", "lightFormat", "_index", "_index2", "_index3", "formattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "date_", "tokens", "substring", "firstCharacter", "cleanEscapedString", "formatter", "input", "matches", "require_milliseconds", "__commonJSMin", "exports", "milliseconds", "_index", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "totalDays", "totalSeconds", "require_millisecondsToHours", "__commonJSMin", "exports", "millisecondsToHours", "_index", "milliseconds", "hours", "require_millisecondsToMinutes", "__commonJSMin", "exports", "millisecondsToMinutes", "_index", "milliseconds", "minutes", "require_millisecondsToSeconds", "__commonJSMin", "exports", "millisecondsToSeconds", "_index", "milliseconds", "seconds", "require_minutesToHours", "__commonJSMin", "exports", "minutesToHours", "_index", "minutes", "hours", "require_minutesToMilliseconds", "__commonJSMin", "exports", "minutesToMilliseconds", "_index", "minutes", "require_minutesToSeconds", "__commonJSMin", "exports", "minutesToSeconds", "_index", "minutes", "require_monthsToQuarters", "__commonJSMin", "exports", "monthsToQuarters", "_index", "months", "quarters", "require_monthsToYears", "__commonJSMin", "exports", "monthsToYears", "_index", "months", "years", "require_nextDay", "__commonJSMin", "exports", "nextDay", "_index", "_index2", "date", "day", "options", "delta", "require_nextFriday", "__commonJSMin", "exports", "nextFriday", "_index", "date", "options", "require_nextMonday", "__commonJSMin", "exports", "nextMonday", "_index", "date", "options", "require_nextSaturday", "__commonJSMin", "exports", "nextSaturday", "_index", "date", "options", "require_nextSunday", "__commonJSMin", "exports", "nextSunday", "_index", "date", "options", "require_nextThursday", "__commonJSMin", "exports", "nextThursday", "_index", "date", "options", "require_nextTuesday", "__commonJSMin", "exports", "nextTuesday", "_index", "date", "options", "require_nextWednesday", "__commonJSMin", "exports", "nextWednesday", "_index", "date", "options", "require_parseISO", "__commonJSMin", "exports", "parseISO", "_index", "_index2", "_index3", "argument", "options", "invalidDate", "additionalDigits", "dateStrings", "splitDateString", "date", "parseYearResult", "parseYear", "parseDate", "timestamp", "time", "offset", "parseTime", "parseTimezone", "tmpDate", "result", "patterns", "dateRegex", "timeRegex", "timezoneRegex", "dateString", "array", "timeString", "token", "regex", "captures", "year", "century", "isWeekDate", "dayOfYear", "parseDateUnit", "month", "day", "week", "dayOfWeek", "validateWeekDate", "dayOfISOWeekYear", "validateDate", "validateDayOfYearDate", "value", "hours", "parseTimeUnit", "minutes", "seconds", "validateTime", "timezoneString", "sign", "validateTimezone", "isoWeekYear", "fourthOfJanuaryDay", "diff", "daysInMonths", "isLeapYearIndex", "_year", "_hours", "require_parseJSON", "__commonJSMin", "exports", "parseJSON", "_index", "dateStr", "options", "parts", "require_previousDay", "__commonJSMin", "exports", "previousDay", "_index", "_index2", "date", "day", "options", "delta", "require_previousFriday", "__commonJSMin", "exports", "previousFriday", "_index", "date", "options", "require_previousMonday", "__commonJSMin", "exports", "previousMonday", "_index", "date", "options", "require_previousSaturday", "__commonJSMin", "exports", "previousSaturday", "_index", "date", "options", "require_previousSunday", "__commonJSMin", "exports", "previousSunday", "_index", "date", "options", "require_previousThursday", "__commonJSMin", "exports", "previousThursday", "_index", "date", "options", "require_previousTuesday", "__commonJSMin", "exports", "previousTuesday", "_index", "date", "options", "require_previousWednesday", "__commonJSMin", "exports", "previousWednesday", "_index", "date", "options", "require_quartersToMonths", "__commonJSMin", "exports", "quartersToMonths", "_index", "quarters", "require_quartersToYears", "__commonJSMin", "exports", "quartersToYears", "_index", "quarters", "years", "require_roundToNearestHours", "__commonJSMin", "exports", "roundToNearestHours", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalMinutes", "fractionalSeconds", "fractionalMilliseconds", "hours", "method", "roundedHours", "require_roundToNearestMinutes", "__commonJSMin", "exports", "roundToNearestMinutes", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalSeconds", "fractionalMilliseconds", "minutes", "method", "roundedMinutes", "require_secondsToHours", "__commonJSMin", "exports", "secondsToHours", "_index", "seconds", "hours", "require_secondsToMilliseconds", "__commonJSMin", "exports", "secondsToMilliseconds", "_index", "seconds", "require_secondsToMinutes", "__commonJSMin", "exports", "secondsToMinutes", "_index", "seconds", "minutes", "require_setMonth", "__commonJSMin", "exports", "setMonth", "_index", "_index2", "_index3", "date", "month", "options", "_date", "year", "day", "midMonth", "daysInMonth", "require_set", "__commonJSMin", "exports", "set", "_index", "_index2", "_index3", "date", "values", "options", "_date", "require_setDate", "__commonJSMin", "exports", "setDate", "_index", "date", "dayOfMonth", "options", "_date", "require_setDayOfYear", "__commonJSMin", "exports", "setDayOfYear", "_index", "date", "dayOfYear", "options", "date_", "require_setDefaultOptions", "__commonJSMin", "exports", "setDefaultOptions", "_index", "options", "result", "defaultOptions", "property", "require_setHours", "__commonJSMin", "exports", "setHours", "_index", "date", "hours", "options", "_date", "require_setMilliseconds", "__commonJSMin", "exports", "setMilliseconds", "_index", "date", "milliseconds", "options", "_date", "require_setMinutes", "__commonJSMin", "exports", "setMinutes", "_index", "date", "minutes", "options", "date_", "require_setQuarter", "__commonJSMin", "exports", "setQuarter", "_index", "_index2", "date", "quarter", "options", "date_", "oldQuarter", "diff", "require_setSeconds", "__commonJSMin", "exports", "setSeconds", "_index", "date", "seconds", "options", "_date", "require_setWeekYear", "__commonJSMin", "exports", "setWeekYear", "_index", "_index2", "_index3", "_index4", "_index5", "date", "weekYear", "options", "defaultOptions", "firstWeekContainsDate", "diff", "firstWeek", "date_", "require_setYear", "__commonJSMin", "exports", "setYear", "_index", "_index2", "date", "year", "options", "date_", "require_startOfDecade", "__commonJSMin", "exports", "startOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_startOfToday", "__commonJSMin", "exports", "startOfToday", "_index", "options", "require_startOfTomorrow", "__commonJSMin", "exports", "startOfTomorrow", "_index", "_index2", "options", "now", "year", "month", "day", "date", "require_startOfYesterday", "__commonJSMin", "exports", "startOfYesterday", "_index", "options", "now", "year", "month", "day", "date", "require_subMonths", "__commonJSMin", "exports", "subMonths", "_index", "date", "amount", "options", "require_sub", "__commonJSMin", "exports", "sub", "_index", "_index2", "_index3", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "withoutMonths", "withoutDays", "minutesToSub", "msToSub", "require_subBusinessDays", "__commonJSMin", "exports", "subBusinessDays", "_index", "date", "amount", "options", "require_subHours", "__commonJSMin", "exports", "subHours", "_index", "date", "amount", "options", "require_subMilliseconds", "__commonJSMin", "exports", "subMilliseconds", "_index", "date", "amount", "options", "require_subMinutes", "__commonJSMin", "exports", "subMinutes", "_index", "date", "amount", "options", "require_subQuarters", "__commonJSMin", "exports", "subQuarters", "_index", "date", "amount", "options", "require_subSeconds", "__commonJSMin", "exports", "subSeconds", "_index", "date", "amount", "options", "require_subWeeks", "__commonJSMin", "exports", "subWeeks", "_index", "date", "amount", "options", "require_subYears", "__commonJSMin", "exports", "subYears", "_index", "date", "amount", "options", "require_weeksToDays", "__commonJSMin", "exports", "weeksToDays", "_index", "weeks", "require_yearsToDays", "__commonJSMin", "exports", "yearsToDays", "_index", "years", "require_yearsToMonths", "__commonJSMin", "exports", "yearsToMonths", "_index", "years", "require_yearsToQuarters", "__commonJSMin", "exports", "yearsToQuarters", "_index", "years", "require_date_fns", "__commonJSMin", "exports", "_index", "key", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "_index11", "_index12", "_index13", "_index14", "_index15", "_index16", "_index17", "_index18", "_index19", "_index20", "_index21", "_index22", "_index23", "_index24", "_index25", "_index26", "_index27", "_index28", "_index29", "_index30", "_index31", "_index32", "_index33", "_index34", "_index35", "_index36", "_index37", "_index38", "_index39", "_index40", "_index41", "_index42", "_index43", "_index44", "_index45", "_index46", "_index47", "_index48", "_index49", "_index50", "_index51", "_index52", "_index53", "_index54", "_index55", "_index56", "_index57", "_index58", "_index59", "_index60", "_index61", "_index62", "_index63", "_index64", "_index65", "_index66", "_index67", "_index68", "_index69", "_index70", "_index71", "_index72", "_index73", "_index74", "_index75", "_index76", "_index77", "_index78", "_index79", "_index80", "_index81", "_index82", "_index83", "_index84", "_index85", "_index86", "_index87", "_index88", "_index89", "_index90", "_index91", "_index92", "_index93", "_index94", "_index95", "_index96", "_index97", "_index98", "_index99", "_index100", "_index101", "_index102", "_index103", "_index104", "_index105", "_index106", "_index107", "_index108", "_index109", "_index110", "_index111", "_index112", "_index113", "_index114", "_index115", "_index116", "_index117", "_index118", "_index119", "_index120", "_index121", "_index122", "_index123", "_index124", "_index125", "_index126", "_index127", "_index128", "_index129", "_index130", "_index131", "_index132", "_index133", "_index134", "_index135", "_index136", "_index137", "_index138", "_index139", "_index140", "_index141", "_index142", "_index143", "_index144", "_index145", "_index146", "_index147", "_index148", "_index149", "_index150", "_index151", "_index152", "_index153", "_index154", "_index155", "_index156", "_index157", "_index158", "_index159", "_index160", "_index161", "_index162", "_index163", "_index164", "_index165", "_index166", "_index167", "_index168", "_index169", "_index170", "_index171", "_index172", "_index173", "_index174", "_index175", "_index176", "_index177", "_index178", "_index179", "_index180", "_index181", "_index182", "_index183", "_index184", "_index185", "_index186", "_index187", "_index188", "_index189", "_index190", "_index191", "_index192", "_index193", "_index194", "_index195", "_index196", "_index197", "_index198", "_index199", "_index200", "_index201", "_index202", "_index203", "_index204", "_index205", "_index206", "_index207", "_index208", "_index209", "_index210", "_index211", "_index212", "_index213", "_index214", "_index215", "_index216", "_index217", "_index218", "_index219", "_index220", "_index221", "_index222", "_index223", "_index224", "_index225", "_index226", "_index227", "_index228", "_index229", "_index230", "_index231", "_index232", "_index233", "_index234", "_index235", "_index236", "_index237", "_index238", "_index239", "_index240", "_index241", "_index242", "_index243", "_index244", "_index245", "require_utils", "__commonJSMin", "exports", "module", "readdir", "stat", "unlink", "symlink", "lstat", "readlink", "dirname", "join", "format", "addDays", "addHours", "parse", "isValid", "parseSize", "size", "multiplier", "match", "unit", "parseFrequency", "frequency", "today", "start", "getNextDay", "getNextHour", "getNextCustom", "validateLimitOptions", "limit", "time", "getNext", "getFileName", "fileVal", "buildFileName", "date", "lastNumber", "extension", "dateStr", "extensionStr", "identifyLogFile", "checkedFileName", "dateFormat", "baseFileNameStr", "checkFileNameSegments", "expectedSegmentCount", "chkExtension", "chkFileNumber", "fileNumber", "fileTime", "d", "getFileSize", "filePath", "detectLastNumber", "fileName", "readFileTrailingNumbers", "a", "b", "folder", "numbers", "file", "isMatchingTime", "number", "extractTrailingNumber", "extractFileName", "birthtimeMs", "removeOldFiles", "count", "removeOtherLogFiles", "baseFile", "createdFileNames", "newFileName", "files", "pathSegments", "fileEntry", "f", "i", "j", "filesToRemove", "checkSymlink", "linkPath", "stats", "existingTarget", "createSymlink", "validateDateFormat", "formatStr", "parseDate", "frequencySpec", "parseStart", "require_pino_roll", "__commonJSMin", "exports", "module", "SonicBoom", "buildFileName", "removeOldFiles", "createSymlink", "detectLastNumber", "parseSize", "parseFrequency", "getNext", "getFileSize", "validateLimitOptions", "parseDate", "validateDateFormat", "file", "size", "frequency", "extension", "limit", "symlink", "dateFormat", "opts", "frequencySpec", "date", "number", "fileName", "createdFileNames", "currentSize", "maxSize", "destination", "rollTimeout", "scheduleRoll", "writtenSize", "roll", "prevDate"] +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..773ccbf03f49d7198d6e92d885ae92ec72907ddd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js", "../../node_modules/.pnpm/pino-abstract-transport@2.0.0/node_modules/pino-abstract-transport/index.js", "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport-stream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/worker.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/esm`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.mjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.mjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.mjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.mjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "/*\nCopyright (c) 2014-2021, Matteo Collina \n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\n'use strict'\n\nconst { Transform } = require('stream')\nconst { StringDecoder } = require('string_decoder')\nconst kLast = Symbol('last')\nconst kDecoder = Symbol('decoder')\n\nfunction transform (chunk, enc, cb) {\n let list\n if (this.overflow) { // Line buffer is full. Skip to start of next line.\n const buf = this[kDecoder].write(chunk)\n list = buf.split(this.matcher)\n\n if (list.length === 1) return cb() // Line ending not found. Discard entire chunk.\n\n // Line ending found. Discard trailing fragment of previous line and reset overflow state.\n list.shift()\n this.overflow = false\n } else {\n this[kLast] += this[kDecoder].write(chunk)\n list = this[kLast].split(this.matcher)\n }\n\n this[kLast] = list.pop()\n\n for (let i = 0; i < list.length; i++) {\n try {\n push(this, this.mapper(list[i]))\n } catch (error) {\n return cb(error)\n }\n }\n\n this.overflow = this[kLast].length > this.maxLength\n if (this.overflow && !this.skipOverflow) {\n cb(new Error('maximum buffer reached'))\n return\n }\n\n cb()\n}\n\nfunction flush (cb) {\n // forward any gibberish left in there\n this[kLast] += this[kDecoder].end()\n\n if (this[kLast]) {\n try {\n push(this, this.mapper(this[kLast]))\n } catch (error) {\n return cb(error)\n }\n }\n\n cb()\n}\n\nfunction push (self, val) {\n if (val !== undefined) {\n self.push(val)\n }\n}\n\nfunction noop (incoming) {\n return incoming\n}\n\nfunction split (matcher, mapper, options) {\n // Set defaults for any arguments not supplied.\n matcher = matcher || /\\r?\\n/\n mapper = mapper || noop\n options = options || {}\n\n // Test arguments explicitly.\n switch (arguments.length) {\n case 1:\n // If mapper is only argument.\n if (typeof matcher === 'function') {\n mapper = matcher\n matcher = /\\r?\\n/\n // If options is only argument.\n } else if (typeof matcher === 'object' && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {\n options = matcher\n matcher = /\\r?\\n/\n }\n break\n\n case 2:\n // If mapper and options are arguments.\n if (typeof matcher === 'function') {\n options = mapper\n mapper = matcher\n matcher = /\\r?\\n/\n // If matcher and options are arguments.\n } else if (typeof mapper === 'object') {\n options = mapper\n mapper = noop\n }\n }\n\n options = Object.assign({}, options)\n options.autoDestroy = true\n options.transform = transform\n options.flush = flush\n options.readableObjectMode = true\n\n const stream = new Transform(options)\n\n stream[kLast] = ''\n stream[kDecoder] = new StringDecoder('utf8')\n stream.matcher = matcher\n stream.mapper = mapper\n stream.maxLength = options.maxLength\n stream.skipOverflow = options.skipOverflow || false\n stream.overflow = false\n stream._destroy = function (err, cb) {\n // Weird Node v12 bug that we need to work around\n this._writableState.errorEmitted = false\n cb(err)\n }\n\n return stream\n}\n\nmodule.exports = split\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst split = require('split2')\nconst { Duplex } = require('stream')\nconst { parentPort, workerData } = require('worker_threads')\n\nfunction createDeferred () {\n let resolve\n let reject\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve\n reject = _reject\n })\n promise.resolve = resolve\n promise.reject = reject\n return promise\n}\n\nmodule.exports = function build (fn, opts = {}) {\n const waitForConfig = opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig === true\n const parseLines = opts.parse === 'lines'\n const parseLine = typeof opts.parseLine === 'function' ? opts.parseLine : JSON.parse\n const close = opts.close || defaultClose\n const stream = split(function (line) {\n let value\n\n try {\n value = parseLine(line)\n } catch (error) {\n this.emit('unknown', line, error)\n return\n }\n\n if (value === null) {\n this.emit('unknown', line, 'Null value ignored')\n return\n }\n\n if (typeof value !== 'object') {\n value = {\n data: value,\n time: Date.now()\n }\n }\n\n if (stream[metadata]) {\n stream.lastTime = value.time\n stream.lastLevel = value.level\n stream.lastObj = value\n }\n\n if (parseLines) {\n return line\n }\n\n return value\n }, { autoDestroy: true })\n\n stream._destroy = function (err, cb) {\n const promise = close(err, cb)\n if (promise && typeof promise.then === 'function') {\n promise.then(cb, cb)\n }\n }\n\n if (opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig !== true) {\n setImmediate(() => {\n stream.emit('error', new Error('This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.'))\n })\n }\n\n if (opts.metadata !== false) {\n stream[metadata] = true\n stream.lastTime = 0\n stream.lastLevel = 0\n stream.lastObj = null\n }\n\n if (waitForConfig) {\n let pinoConfig = {}\n const configReceived = createDeferred()\n parentPort.on('message', function handleMessage (message) {\n if (message.code === 'PINO_CONFIG') {\n pinoConfig = message.config\n configReceived.resolve()\n parentPort.off('message', handleMessage)\n }\n })\n\n Object.defineProperties(stream, {\n levels: {\n get () { return pinoConfig.levels }\n },\n messageKey: {\n get () { return pinoConfig.messageKey }\n },\n errorKey: {\n get () { return pinoConfig.errorKey }\n }\n })\n\n return configReceived.then(finish)\n }\n\n return finish()\n\n function finish () {\n let res = fn(stream)\n\n if (res && typeof res.catch === 'function') {\n res.catch((err) => {\n stream.destroy(err)\n })\n\n // set it to null to not retain a reference to the promise\n res = null\n } else if (opts.enablePipelining && res) {\n return Duplex.from({ writable: stream, readable: res })\n }\n\n return stream\n }\n}\n\nfunction defaultClose (err, cb) {\n process.nextTick(cb, err)\n}\n", "/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\n\nmodule.exports = loadTransportStreamBuilder\n\n/**\n * Loads & returns a function to build transport streams\n * @param {string} target\n * @returns {Promise>}\n * @throws {Error} In case the target module does not export a function\n */\nasync function loadTransportStreamBuilder (target) {\n let fn\n try {\n const toLoad = target.startsWith('file://') ? target : 'file://' + target\n\n if (toLoad.endsWith('.ts') || toLoad.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env && process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n fn = realRequire(decodeURIComponent(target))\n } else {\n fn = (await realImport(toLoad))\n }\n } catch (error) {\n // See this PR for details: https://github.com/pinojs/thread-stream/pull/34\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND')) {\n fn = realRequire(target)\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n fn = realRequire(decodeURIComponent(target))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn !== 'function') throw Error('exported worker is not a function')\n\n return fn\n}\n", "'use strict'\n\nconst EE = require('node:events')\nconst { pipeline, PassThrough } = require('node:stream')\nconst pino = require('../pino.js')\nconst build = require('pino-abstract-transport')\nconst loadTransportStreamBuilder = require('./transport-stream')\n\n// This file is not checked by the code coverage tool,\n// as it is not reliable.\n\n/* istanbul ignore file */\n\n/*\n * > Multiple targets & pipelines\n *\n *\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2502 p \u2502\n * \u2502 \u2502 \u2502 i \u2502\n * \u2502 target \u2502 \u2502 n \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 o \u2502\n * \u2502 targets \u2502 target \u2502 \u2502 . \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 m \u2502 source\n * \u2502 \u2502 target \u2502 \u2502 u \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 l \u2502 \u2502write\n * \u2502 \u2502 \u2502 \u2502 t \u2502 \u25BC\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 i \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 s \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 t \u2502 write\u2502 Thread \u2502\n * \u2502 \u2502 \u2502 \u2502 r \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 Stream \u2502\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 e \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 a \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 m \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2518\n *\n *\n *\n * > One single pipeline or target\n *\n *\n * source\n * \u2502\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502write\n * \u2502 \u2502 \u25BC\n * \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 targets \u2502 target \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 targets \u2502 pipeline \u2502 \u2502 \u2502 \u2502 Thread \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2524 \u2502 Stream \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 write\u2502 \u2502\n * \u2502 \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 pipeline \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2502\n * \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n */\n\nmodule.exports = async function ({ targets, pipelines, levels, dedupe }) {\n const targetStreams = []\n\n // Process targets\n if (targets && targets.length) {\n targets = await Promise.all(targets.map(async (t) => {\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return {\n level: t.level,\n stream\n }\n }))\n\n targetStreams.push(...targets)\n }\n\n // Process pipelines\n if (pipelines && pipelines.length) {\n pipelines = await Promise.all(\n pipelines.map(async (p) => {\n let level\n const pipeDests = await Promise.all(\n p.map(async (t) => {\n // level assigned to pipeline is duplicated over all its targets, just store it\n level = t.level\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return stream\n }\n ))\n\n return {\n level,\n stream: createPipeline(pipeDests)\n }\n })\n )\n targetStreams.push(...pipelines)\n }\n\n // Skip building the multistream step if either one single pipeline or target is defined and\n // return directly the stream instance back to TreadStream.\n // This is equivalent to define either:\n //\n // pino.transport({ target: ... })\n //\n // OR\n //\n // pino.transport({ pipeline: ... })\n if (targetStreams.length === 1) {\n return targetStreams[0].stream\n } else {\n return build(process, {\n parse: 'lines',\n metadata: true,\n close (err, cb) {\n let expected = 0\n for (const transport of targetStreams) {\n expected++\n transport.stream.on('close', closeCb)\n transport.stream.end()\n }\n\n function closeCb () {\n if (--expected === 0) {\n cb(err)\n }\n }\n }\n })\n }\n\n // TODO: Why split2 was not used for pipelines?\n function process (stream) {\n const multi = pino.multistream(targetStreams, { levels, dedupe })\n // TODO manage backpressure\n stream.on('data', function (chunk) {\n const { lastTime, lastMsg, lastObj, lastLevel } = this\n multi.lastLevel = lastLevel\n multi.lastTime = lastTime\n multi.lastMsg = lastMsg\n multi.lastObj = lastObj\n\n // TODO handle backpressure\n multi.write(chunk + '\\n')\n })\n }\n\n /**\n * Creates a pipeline using the provided streams and return an instance of `PassThrough` stream\n * as a source for the pipeline.\n *\n * @param {(TransformStream|WritableStream)[]} streams An array of streams.\n * All intermediate streams in the array *MUST* be `Transform` streams and only the last one `Writable`.\n * @returns A `PassThrough` stream instance representing the source stream of the pipeline\n */\n function createPipeline (streams) {\n const ee = new EE()\n const stream = new PassThrough({\n autoDestroy: true,\n destroy (_, cb) {\n ee.on('error', cb)\n ee.on('closed', cb)\n }\n })\n\n pipeline(stream, ...streams, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n ee.emit('error', err)\n return\n }\n\n ee.emit('closed')\n })\n\n return stream\n }\n}\n"], + "mappings": "uTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAIV,IAAME,EAAQF,EAAI,MAGlB,GAAI,OAAOE,GAAU,WAAY,CAE/B,IAAMC,EAAcH,EAAI,MAAM,EAE9B,OAAOD,EAAYI,CAAW,EAC1BA,EACA,MACN,KACE,QAAOJ,EA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,EAEMlB,CACT,CACF", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "require_split2", "__commonJSMin", "exports", "module", "Transform", "StringDecoder", "kLast", "kDecoder", "transform", "chunk", "enc", "cb", "list", "push", "error", "flush", "self", "val", "noop", "incoming", "split", "matcher", "mapper", "options", "stream", "err", "require_pino_abstract_transport", "__commonJSMin", "exports", "module", "metadata", "split", "Duplex", "parentPort", "workerData", "createDeferred", "resolve", "reject", "promise", "_resolve", "_reject", "fn", "opts", "waitForConfig", "parseLines", "parseLine", "close", "defaultClose", "stream", "line", "value", "error", "err", "cb", "pinoConfig", "configReceived", "handleMessage", "message", "finish", "res", "require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "__require", "require_transport_stream", "__commonJSMin", "exports", "module", "realImport", "realRequire", "loadTransportStreamBuilder", "target", "fn", "toLoad", "error", "require_worker", "__commonJSMin", "exports", "module", "EE", "pipeline", "PassThrough", "pino", "build", "loadTransportStreamBuilder", "targets", "pipelines", "levels", "dedupe", "targetStreams", "t", "stream", "p", "level", "pipeDests", "createPipeline", "process", "err", "cb", "expected", "transport", "closeCb", "multi", "chunk", "lastTime", "lastMsg", "lastObj", "lastLevel", "streams", "ee", "_"] +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0a8e3baa8b9ea9754bdd19aa8ebb235fc5d0073c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs @@ -0,0 +1,274 @@ +var My=Object.create;var Pa=Object.defineProperty;var $y=Object.getOwnPropertyDescriptor;var Hy=Object.getOwnPropertyNames;var Gy=Object.getPrototypeOf,Wy=Object.prototype.hasOwnProperty;var X=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Me=(r,e)=>()=>(r&&(e=r(r=0)),e);var z=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Af=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},zy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hy(e))!Wy.call(r,o)&&o!==t&&Pa(r,o,{get:()=>e[o],enumerable:!(n=$y(e,o))||n.enumerable});return r};var zr=(r,e,t)=>(t=r!=null?My(Gy(r)):{},zy(e||!r||!r.__esModule?Pa(t,"default",{value:r,enumerable:!0}):t,r));var Df=z((sA,lo)=>{lo.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;lo.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uA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uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;lo.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE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\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uF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\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00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EA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Ba=z((oA,Sf)=>{var xa=Df();Sf.exports={isSpaceSeparator(r){return typeof r=="string"&&xa.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||xa.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||xa.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}}});var Ff=z((iA,kf)=>{var $e=Ba(),Na,Ze,cr,ho,vr,Pt,He,La,os;kf.exports=function(e,t){Na=String(e),Ze="start",cr=[],ho=0,vr=1,Pt=0,He=void 0,La=void 0,os=void 0;do He=Jy(),Yy[Ze]();while(He.type!=="eof");return typeof t=="function"?qa({"":os},"",t):os};function qa(r,e,t){let n=r[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let o=0;o0;){let t=lr();if(!$e.isHexDigit(t))throw Pe($());r+=$()}return String.fromCodePoint(parseInt(r,16))}var Yy={start(){if(He.type==="eof")throw Vr();Ia()},beforePropertyName(){switch(He.type){case"identifier":case"string":La=He.value,Ze="afterPropertyName";return;case"punctuator":fo();return;case"eof":throw Vr()}},afterPropertyName(){if(He.type==="eof")throw Vr();Ze="beforePropertyValue"},beforePropertyValue(){if(He.type==="eof")throw Vr();Ia()},beforeArrayValue(){if(He.type==="eof")throw Vr();if(He.type==="punctuator"&&He.value==="]"){fo();return}Ia()},afterPropertyValue(){if(He.type==="eof")throw Vr();switch(He.value){case",":Ze="beforePropertyName";return;case"}":fo()}},afterArrayValue(){if(He.type==="eof")throw Vr();switch(He.value){case",":Ze="beforeArrayValue";return;case"]":fo()}},end(){}};function Ia(){let r;switch(He.type){case"punctuator":switch(He.value){case"{":r={};break;case"[":r=[];break}break;case"null":case"boolean":case"numeric":case"string":r=He.value;break}if(os===void 0)os=r;else{let e=cr[cr.length-1];Array.isArray(e)?e.push(r):Object.defineProperty(e,La,{value:r,writable:!0,enumerable:!0,configurable:!0})}if(r!==null&&typeof r=="object")cr.push(r),Array.isArray(r)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=cr[cr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function fo(){cr.pop();let r=cr[cr.length-1];r==null?Ze="end":Array.isArray(r)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Pe(r){return po(r===void 0?`JSON5: invalid end of input at ${vr}:${Pt}`:`JSON5: invalid character '${Rf(r)}' at ${vr}:${Pt}`)}function Vr(){return po(`JSON5: invalid end of input at ${vr}:${Pt}`)}function vf(){return Pt-=5,po(`JSON5: invalid identifier character at ${vr}:${Pt}`)}function Xy(r){console.warn(`JSON5: '${Rf(r)}' in strings is not valid ECMAScript; consider escaping`)}function Rf(r){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[r])return e[r];if(r<" "){let t=r.charCodeAt(0).toString(16);return"\\x"+("00"+t).substring(t.length)}return r}function po(r){let e=new SyntaxError(r);return e.lineNumber=vr,e.columnNumber=Pt,e}});var Pf=z((aA,Of)=>{var Ua=Ba();Of.exports=function(e,t,n){let o=[],a="",u,l,f="",h;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,h=t.quote,t=t.replacer),typeof t=="function")l=t;else if(Array.isArray(t)){u=[];for(let w of t){let g;typeof w=="string"?g=w:(typeof w=="number"||w instanceof String||w instanceof Number)&&(g=String(w)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),f=" ".substr(0,n)):typeof n=="string"&&(f=n.substr(0,10)),d("",{"":e});function d(w,g){let C=g[w];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(w):typeof C.toJSON=="function"&&(C=C.toJSON(w))),l&&(C=l.call(g,w,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return _(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?v(C):E(C)}function _(w){let g={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},R="";for(let N=0;Ng[N]=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=u||Object.keys(w),R=[];for(let N of C){let j=d(N,w);if(j!==void 0){let L=P(N)+":";f!==""&&(L+=" "),L+=j,R.push(L)}}let S;if(R.length===0)S="{}";else{let N;if(f==="")N=R.join(","),S="{"+N+"}";else{let j=`, +`+a;N=R.join(j),S=`{ +`+a+N+`, +`+g+"}"}}return o.pop(),a=g,S}function P(w){if(w.length===0)return _(w,!0);let g=String.fromCodePoint(w.codePointAt(0));if(!Ua.isIdStartChar(g))return _(w,!0);for(let C=g.length;C=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=[];for(let S=0;S{var Qy=Ff(),Zy=Pf(),e0={parse:Qy,stringify:Zy};xf.exports=e0});var Ga=z(($A,Yf)=>{"use strict";var So=Object.prototype.hasOwnProperty,Kf=Object.prototype.toString,Hf=Object.defineProperty,Gf=Object.getOwnPropertyDescriptor,Wf=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Kf.call(e)==="[object Array]"},zf=function(e){if(!e||Kf.call(e)!=="[object Object]")return!1;var t=So.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&So.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!n)return!1;var o;for(o in e);return typeof o>"u"||So.call(e,o)},Jf=function(e,t){Hf&&t.name==="__proto__"?Hf(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Vf=function(e,t){if(t==="__proto__")if(So.call(e,t)){if(Gf)return Gf(e,t).value}else return;return e[t]};Yf.exports=function r(){var e,t,n,o,a,u,l=arguments[0],f=1,h=arguments.length,d=!1;for(typeof l=="boolean"&&(d=l,l=arguments[1]||{},f=2),(l==null||typeof l!="object"&&typeof l!="function")&&(l={});f{y0.exports={name:"gaxios",version:"7.1.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^20.0.0","stream-browserify":"^3.0.0",tmp:"0.2.3","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var Zf=z((GA,Qf)=>{"use strict";var _0=Xf();Qf.exports={pkg:_0}});var Ja=z(Et=>{"use strict";var td=Et&&Et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Et,"__esModule",{value:!0});Et.GaxiosError=Et.GAXIOS_ERROR_SYMBOL=void 0;Et.defaultErrorRedactor=rd;var ed=td(Ga()),C0=td(Zf()),Wa=C0.default.pkg;Et.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Wa.name}-gaxios-error`);var za=class r extends Error{config;response;code;status;error;[Et.GAXIOS_ERROR_SYMBOL]=Wa.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Et.GAXIOS_ERROR_SYMBOL in e&&e[Et.GAXIOS_ERROR_SYMBOL]===Wa.version?!0:Function.prototype[Symbol.hasInstance].call(r,e)}constructor(e,t,n,o){if(super(e,{cause:o}),this.config=t,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,ed.default)(!0,{},t),this.response&&(this.response.config=(0,ed.default)(!0,{},this.response.config)),this.response){try{this.response.data=b0(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let n=t;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let u=[];for(let l of e.data.error.errors)typeof l=="object"&&"message"in l&&typeof l.message=="string"&&u.push(l.message);return Object.assign({message:u.join(` +`)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};Et.GaxiosError=za;function b0(r,e){switch(r){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function rd(r){let e="< - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((u,l)=>{(/^authentication$/i.test(l)||/^authorization$/i.test(l)||/secret/i.test(l))&&a.set(l,e)})}function n(a,u){if(typeof a=="object"&&a!==null&&typeof a[u]=="string"){let l=a[u];(/grant_type=/i.test(l)||/assertion=/i.test(l)||/secret/i.test(l))&&(a[u]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((u,l)=>{(["grant_type","assertion"].includes(l)||/secret/.test(l))&&a.set(l,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return r.config&&(t(r.config.headers),n(r.config,"data"),o(r.config.data),n(r.config,"body"),o(r.config.body),r.config.url.searchParams.has("token")&&r.config.url.searchParams.set("token",e),r.config.url.searchParams.has("client_secret")&&r.config.url.searchParams.set("client_secret",e)),r.response&&(rd({config:r.response.config}),t(r.response.headers),r.response.bodyUsed&&(n(r.response,"data"),o(r.response.data))),r}});var sd=z(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.getRetryConfig=E0;async function E0(r){let e=nd(r);if(!r||!r.config||!e&&!r.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,r.config.retryConfig=e,!await(e.shouldRetry||w0)(r))return{shouldRetry:!1,config:r.config};let o=A0(e);r.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(r,o):new Promise(u=>{setTimeout(u,o)});return e.onRetryAttempt&&await e.onRetryAttempt(r),await a,{shouldRetry:!0,config:r.config}}function w0(r){let e=nd(r);if(r.config.signal?.aborted&&r.code!=="TimeoutError"||r.code==="AbortError"||!e||e.retry===0||!r.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(r.config.method?.toUpperCase()||"GET"))return!1;if(r.response&&r.response.status){let t=!1;for(let[n,o]of e.statusCodesToRetry){let a=r.response.status;if(a>=n&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function nd(r){if(r&&r.config&&r.config.retryConfig)return r.config.retryConfig}function A0(r){let t=(r.currentRetryAttempt?0:r.retryDelay??100)+(Math.pow(r.retryDelayMultiplier,r.currentRetryAttempt)-1)/2*1e3,n=r.totalTimeout-(Date.now()-r.timeOfFirstRequest);return Math.min(t,n,r.maxRetryDelay)}});var Ya=z(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.GaxiosInterceptorManager=void 0;var Ka=class extends Set{};vo.GaxiosInterceptorManager=Ka});var id=z((VA,od)=>{var bn=1e3,En=bn*60,wn=En*60,Kr=wn*24,D0=Kr*7,S0=Kr*365.25;od.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return v0(r);if(t==="number"&&isFinite(r))return e.long?R0(r):T0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function v0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*S0;case"weeks":case"week":case"w":return t*D0;case"days":case"day":case"d":return t*Kr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*wn;case"minutes":case"minute":case"mins":case"min":case"m":return t*En;case"seconds":case"second":case"secs":case"sec":case"s":return t*bn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function T0(r){var e=Math.abs(r);return e>=Kr?Math.round(r/Kr)+"d":e>=wn?Math.round(r/wn)+"h":e>=En?Math.round(r/En)+"m":e>=bn?Math.round(r/bn)+"s":r+"ms"}function R0(r){var e=Math.abs(r);return e>=Kr?To(r,e,Kr,"day"):e>=wn?To(r,e,wn,"hour"):e>=En?To(r,e,En,"minute"):e>=bn?To(r,e,bn,"second"):r+" ms"}function To(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Xa=z((KA,ad)=>{function k0(r){t.debug=t,t.default=t,t.coerce=f,t.disable=u,t.enable=o,t.enabled=l,t.humanize=id(),t.destroy=h,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let _=0;for(let E=0;E{if(L==="%%")return"%";N++;let K=t.formatters[H];if(typeof K=="function"){let W=g[N];L=K.call(C,W),g.splice(N,1),N--}return L}),t.formatArgs.call(C,g),(C.log||t.log).apply(C,g)}return w.namespace=d,w.useColors=t.useColors(),w.color=t.selectColor(d),w.extend=n,w.destroy=t.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>E!==null?E:(P!==t.namespaces&&(P=t.namespaces,v=t.enabled(d)),v),set:g=>{E=g}}),typeof t.init=="function"&&t.init(w),w}function n(d,_){let E=t(this.namespace+(typeof _>"u"?":":_)+d);return E.log=this.log,E}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let _=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let E of _)E[0]==="-"?t.skips.push(E.slice(1)):t.names.push(E)}function a(d,_){let E=0,P=0,v=-1,w=0;for(;E"-"+_)].join(",");return t.enable(""),d}function l(d){for(let _ of t.skips)if(a(d,_))return!1;for(let _ of t.names)if(a(d,_))return!0;return!1}function f(d){return d instanceof Error?d.stack||d.message:d}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ad.exports=k0});var ud=z((st,Ro)=>{st.formatArgs=O0;st.save=P0;st.load=x0;st.useColors=F0;st.storage=B0();st.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();st.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function F0(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function O0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ro.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function P0(r){try{r?st.storage.setItem("debug",r):st.storage.removeItem("debug")}catch{}}function x0(){let r;try{r=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function B0(){try{return localStorage}catch{}}Ro.exports=Xa()(st);var{formatters:I0}=Ro.exports;I0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ld=z((YA,cd)=>{"use strict";cd.exports=(r,e)=>{e=e||process.argv;let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),o=e.indexOf("--");return n!==-1&&(o===-1?!0:n{"use strict";var N0=X("os"),xt=ld(),Ye=process.env,An;xt("no-color")||xt("no-colors")||xt("color=false")?An=!1:(xt("color")||xt("colors")||xt("color=true")||xt("color=always"))&&(An=!0);"FORCE_COLOR"in Ye&&(An=Ye.FORCE_COLOR.length===0||parseInt(Ye.FORCE_COLOR,10)!==0);function q0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function j0(r){if(An===!1)return 0;if(xt("color=16m")||xt("color=full")||xt("color=truecolor"))return 3;if(xt("color=256"))return 2;if(r&&!r.isTTY&&An!==!0)return 0;let e=An?1:0;if(process.platform==="win32"){let t=N0.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in Ye)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(t=>t in Ye)||Ye.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in Ye)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ye.TEAMCITY_VERSION)?1:0;if(Ye.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ye){let t=parseInt((Ye.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ye.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ye.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ye.TERM)||"COLORTERM"in Ye?1:(Ye.TERM==="dumb",e)}function Qa(r){let e=j0(r);return q0(e)}fd.exports={supportsColor:Qa,stdout:Qa(process.stdout),stderr:Qa(process.stderr)}});var pd=z((Ge,Fo)=>{var L0=X("tty"),ko=X("util");Ge.init=z0;Ge.log=H0;Ge.formatArgs=M0;Ge.save=G0;Ge.load=W0;Ge.useColors=U0;Ge.destroy=ko.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ge.colors=[6,2,3,4,5,1];try{let r=dd();r&&(r.stderr||r).level>=2&&(Ge.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ge.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function U0(){return"colors"in Ge.inspectOpts?!!Ge.inspectOpts.colors:L0.isatty(process.stderr.fd)}function M0(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),a=` ${o};1m${e} \x1B[0m`;r[0]=a+r[0].split(` +`).join(` +`+a),r.push(o+"m+"+Fo.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=$0()+e+" "+r[0]}function $0(){return Ge.inspectOpts.hideDate?"":new Date().toISOString()+" "}function H0(...r){return process.stderr.write(ko.formatWithOptions(Ge.inspectOpts,...r)+` +`)}function G0(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function W0(){return process.env.DEBUG}function z0(r){r.inspectOpts={};let e=Object.keys(Ge.inspectOpts);for(let t=0;te.trim()).join(" ")};hd.O=function(r){return this.inspectOpts.colors=this.useColors,ko.inspect(r,this.inspectOpts)}});var eu=z((QA,Za)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Za.exports=ud():Za.exports=pd()});var yd=z(ot=>{"use strict";var J0=ot&&ot.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),V0=ot&&ot.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),md=ot&&ot.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&J0(e,r,t);return V0(e,r),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var K0=md(X("http")),Y0=md(X("https"));async function gd(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}ot.toBuffer=gd;async function X0(r){let t=(await gd(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let o=n;throw o.message+=` (input: ${t})`,o}}ot.json=X0;function Q0(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?Y0:K0).request(r,e),o=new Promise((a,u)=>{n.once("response",a).once("error",u).end()});return n.then=o.then.bind(o),n}ot.req=Q0});var Ed=z(lt=>{"use strict";var Cd=lt&<.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Z0=lt&<.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),bd=lt&<.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Cd(e,r,t);return Z0(e,r),e},e_=lt&<.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Cd(e,r,t)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var t_=bd(X("net")),_d=bd(X("http")),r_=X("https");e_(yd(),lt);var Gt=Symbol("AgentBaseInternalState"),tu=class extends _d.Agent{constructor(e){super(e),this[Gt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(` +`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new t_.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],o=n.indexOf(t);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?r_.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),u=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(l=>{if(this.decrementSockets(a,u),l instanceof _d.Agent)try{return l.addRequest(e,o)}catch(f){return n(f)}this[Gt].currentSocket=l,super.createSocket(e,t,n)},l=>{this.decrementSockets(a,u),n(l)})}createConnection(){let e=this[Gt].currentSocket;if(this[Gt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Gt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Gt]&&(this[Gt].defaultPort=e)}get protocol(){return this[Gt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Gt]&&(this[Gt].protocol=e)}};lt.Agent=tu});var wd=z(Dn=>{"use strict";var n_=Dn&&Dn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dn,"__esModule",{value:!0});Dn.parseProxyResponse=void 0;var s_=n_(eu()),Oo=(0,s_.default)("https-proxy-agent:parse-proxy-response");function o_(r){return new Promise((e,t)=>{let n=0,o=[];function a(){let d=r.read();d?h(d):r.once("readable",a)}function u(){r.removeListener("end",l),r.removeListener("error",f),r.removeListener("readable",a)}function l(){u(),Oo("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function f(d){u(),Oo("onerror %o",d),t(d)}function h(d){o.push(d),n+=d.length;let _=Buffer.concat(o,n),E=_.indexOf(`\r +\r +`);if(E===-1){Oo("have not received end of HTTP headers yet..."),a();return}let P=_.slice(0,E).toString("ascii").split(`\r +`),v=P.shift();if(!v)return r.destroy(),t(new Error("No header received from proxy CONNECT response"));let w=v.split(" "),g=+w[1],C=w.slice(2).join(" "),R={};for(let S of P){if(!S)continue;let N=S.indexOf(":");if(N===-1)return r.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${S}"`));let j=S.slice(0,N).toLowerCase(),L=S.slice(N+1).trimStart(),H=R[j];typeof H=="string"?R[j]=[H,L]:Array.isArray(H)?H.push(L):R[j]=L}Oo("got proxy server response: %o %o",v,R),u(),e({connect:{statusCode:g,statusText:C,headers:R},buffered:_})}r.on("error",f),r.on("end",l),a()})}Dn.parseProxyResponse=o_});var Rd=z(wt=>{"use strict";var i_=wt&&wt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),a_=wt&&wt.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vd=wt&&wt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&i_(e,r,t);return a_(e,r),e},Td=wt&&wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(wt,"__esModule",{value:!0});wt.HttpsProxyAgent=void 0;var Po=vd(X("net")),Ad=vd(X("tls")),u_=Td(X("assert")),c_=Td(eu()),l_=Ed(),f_=X("url"),d_=wd(),as=(0,c_.default)("https-proxy-agent"),Dd=r=>r.servername===void 0&&r.host&&!Po.isIP(r.host)?{...r,servername:r.host}:r,xo=class extends l_.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new f_.URL(e):e,this.proxyHeaders=t?.headers??{},as("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?Sd(t,"headers"):null,host:n,port:o}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(as("Creating `tls.Socket`: %o",this.connectOpts),o=Ad.connect(Dd(this.connectOpts))):(as("Creating `net.Socket`: %o",this.connectOpts),o=Po.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Po.isIPv6(t.host)?`[${t.host}]`:t.host,l=`CONNECT ${u}:${t.port} HTTP/1.1\r +`;if(n.username||n.password){let E=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(E).toString("base64")}`}a.Host=`${u}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let E of Object.keys(a))l+=`${E}: ${a[E]}\r +`;let f=(0,d_.parseProxyResponse)(o);o.write(`${l}\r +`);let{connect:h,buffered:d}=await f;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",h_),t.secureEndpoint?(as("Upgrading socket connection to TLS"),Ad.connect({...Sd(Dd(t),"host","path","port"),socket:o})):o;o.destroy();let _=new Po.Socket({writable:!1});return _.readable=!0,e.once("socket",E=>{as("Replaying proxy buffer for failed request"),(0,u_.default)(E.listenerCount("data")>0),E.push(d),E.push(null)}),_}};xo.protocols=["http","https"];wt.HttpsProxyAgent=xo;function h_(r){r.resume()}function Sd(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});function p_(r){if(!/^data:/i.test(r))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');r=r.replace(/\r?\n/g,"");let e=r.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=r.substring(5,e).split(";"),n="",o=!1,a=t[0]||"text/plain",u=a;for(let d=1;d{kd=p_});var Pd=z((Bo,Od)=>{(function(r,e){typeof Bo=="object"&&typeof Od<"u"?e(Bo):typeof define=="function"&&define.amd?define(["exports"],e):(r=typeof globalThis<"u"?globalThis:r||self,e(r.WebStreamsPolyfill={}))})(Bo,function(r){"use strict";function e(){}function t(s){return typeof s=="object"&&s!==null||typeof s=="function"}let n=e;function o(s,i){try{Object.defineProperty(s,"name",{value:i,configurable:!0})}catch{}}let a=Promise,u=Promise.prototype.then,l=Promise.reject.bind(a);function f(s){return new a(s)}function h(s){return f(i=>i(s))}function d(s){return l(s)}function _(s,i,c){return u.call(s,i,c)}function E(s,i,c){_(_(s,i,c),void 0,n)}function P(s,i){E(s,i)}function v(s,i){E(s,void 0,i)}function w(s,i,c){return _(s,i,c)}function g(s){_(s,void 0,n)}let C=s=>{if(typeof queueMicrotask=="function")C=queueMicrotask;else{let i=h(void 0);C=c=>_(i,c)}return C(s)};function R(s,i,c){if(typeof s!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(s,i,c)}function S(s,i,c){try{return h(R(s,i,c))}catch(m){return d(m)}}let N=16384;class j{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(i){let c=this._back,m=c;c._elements.length===N-1&&(m={_elements:[],_next:void 0}),c._elements.push(i),m!==c&&(this._back=m,c._next=m),++this._size}shift(){let i=this._front,c=i,m=this._cursor,A=m+1,I=i._elements,U=I[m];return A===N&&(c=i._next,A=0),--this._size,this._cursor=A,i!==c&&(this._front=c),I[m]=void 0,U}forEach(i){let c=this._cursor,m=this._front,A=m._elements;for(;(c!==A.length||m._next!==void 0)&&!(c===A.length&&(m=m._next,A=m._elements,c=0,A.length===0));)i(A[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let L=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),K=Symbol("[[CancelSteps]]"),W=Symbol("[[PullSteps]]"),Ae=Symbol("[[ReleaseSteps]]");function he(s,i){s._ownerReadableStream=i,i._reader=s,i._state==="readable"?de(s):i._state==="closed"?ue(s):Z(s,i._storedError)}function fe(s,i){let c=s._ownerReadableStream;return Ft(c,i)}function ye(s){let i=s._ownerReadableStream;i._state==="readable"?J(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):se(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[Ae](),i._reader=void 0,s._ownerReadableStream=void 0}function re(s){return new TypeError("Cannot "+s+" a stream using a released reader")}function de(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c})}function Z(s,i){de(s),J(s,i)}function ue(s){de(s),oe(s)}function J(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}function se(s,i){Z(s,i)}function oe(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}let Ie=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},je=Math.trunc||function(s){return s<0?Math.ceil(s):Math.floor(s)};function G(s){return typeof s=="object"||typeof s=="function"}function pe(s,i){if(s!==void 0&&!G(s))throw new TypeError(`${i} is not an object.`)}function Ee(s,i){if(typeof s!="function")throw new TypeError(`${i} is not a function.`)}function er(s){return typeof s=="object"&&s!==null||typeof s=="function"}function xe(s,i){if(!er(s))throw new TypeError(`${i} is not an object.`)}function Ne(s,i,c){if(s===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function p(s,i,c){if(s===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function y(s){return Number(s)}function b(s){return s===0?0:s}function x(s){return b(je(s))}function T(s,i){let m=Number.MAX_SAFE_INTEGER,A=Number(s);if(A=b(A),!Ie(A))throw new TypeError(`${i} is not a finite number`);if(A=x(A),A<0||A>m)throw new TypeError(`${i} is outside the accepted range of 0 to ${m}, inclusive`);return!Ie(A)||A===0?0:A}function F(s,i){if(!wr(s))throw new TypeError(`${i} is not a ReadableStream.`)}function q(s){return new M(s)}function D(s,i){s._reader._readRequests.push(i)}function k(s,i,c){let A=s._reader._readRequests.shift();c?A._closeSteps():A._chunkSteps(i)}function B(s){return s._reader._readRequests.length}function O(s){let i=s._reader;return!(i===void 0||!Y(i))}class M{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),F(i,"First parameter"),Ar(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");he(this,i),this._readRequests=new j}get closed(){return Y(this)?this._closedPromise:d(Be("closed"))}cancel(i=void 0){return Y(this)?this._ownerReadableStream===void 0?d(re("cancel")):fe(this,i):d(Be("cancel"))}read(){if(!Y(this))return d(Be("read"));if(this._ownerReadableStream===void 0)return d(re("read from"));let i,c,m=f((I,U)=>{i=I,c=U});return Q(this,{_chunkSteps:I=>i({value:I,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:I=>c(I)}),m}releaseLock(){if(!Y(this))throw Be("releaseLock");this._ownerReadableStream!==void 0&&we(this)}}Object.defineProperties(M.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(M.prototype.cancel,"cancel"),o(M.prototype.read,"read"),o(M.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(M.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Y(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readRequests")?!1:s instanceof M}function Q(s,i){let c=s._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[W](i)}function we(s){ye(s);let i=new TypeError("Reader was released");Fe(s,i)}function Fe(s,i){let c=s._readRequests;s._readRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function Be(s){return new TypeError(`ReadableStreamDefaultReader.prototype.${s} can only be used on a ReadableStreamDefaultReader`)}let be=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class De{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?w(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,m,A=f((U,V)=>{c=U,m=V});return Q(i,{_chunkSteps:U=>{this._ongoingPromise=void 0,C(()=>c({value:U,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ye(i),c({value:void 0,done:!0})},_errorSteps:U=>{this._ongoingPromise=void 0,this._isFinished=!0,ye(i),m(U)}}),A}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let m=fe(c,i);return ye(c),w(m,()=>({value:i,done:!0}))}return ye(c),h({value:i,done:!0})}}let Le={next(){return on(this)?this._asyncIteratorImpl.next():d(an("next"))},return(s){return on(this)?this._asyncIteratorImpl.return(s):d(an("return"))}};Object.setPrototypeOf(Le,be);function sn(s,i){let c=q(s),m=new De(c,i),A=Object.create(Le);return A._asyncIteratorImpl=m,A}function on(s){if(!t(s)||!Object.prototype.hasOwnProperty.call(s,"_asyncIteratorImpl"))return!1;try{return s._asyncIteratorImpl instanceof De}catch{return!1}}function an(s){return new TypeError(`ReadableStreamAsyncIterator.${s} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(s){return s!==s};var tr,Ve,Ue;function Se(s){return s.slice()}function bl(s,i,c,m,A){new Uint8Array(s).set(new Uint8Array(c,m,A),i)}let rr=s=>(typeof s.transfer=="function"?rr=i=>i.transfer():typeof structuredClone=="function"?rr=i=>structuredClone(i,{transfer:[i]}):rr=i=>i,rr(s)),_r=s=>(typeof s.detached=="boolean"?_r=i=>i.detached:_r=i=>i.byteLength===0,_r(s));function El(s,i,c){if(s.slice)return s.slice(i,c);let m=c-i,A=new ArrayBuffer(m);return bl(A,0,s,i,m),A}function qs(s,i){let c=s[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function ig(s){let i={[Symbol.iterator]:()=>s.iterator},c=async function*(){return yield*i}(),m=c.next;return{iterator:c,nextMethod:m,done:!1}}let oa=(Ue=(tr=Symbol.asyncIterator)!==null&&tr!==void 0?tr:(Ve=Symbol.for)===null||Ve===void 0?void 0:Ve.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function wl(s,i="sync",c){if(c===void 0)if(i==="async"){if(c=qs(s,oa),c===void 0){let I=qs(s,Symbol.iterator),U=wl(s,"sync",I);return ig(U)}}else c=qs(s,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let m=R(c,s,[]);if(!t(m))throw new TypeError("The iterator method must return an object");let A=m.next;return{iterator:m,nextMethod:A,done:!1}}function ag(s){let i=R(s.nextMethod,s.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function ug(s){return!!s.done}function cg(s){return s.value}function lg(s){return!(typeof s!="number"||ut(s)||s<0)}function Al(s){let i=El(s.buffer,s.byteOffset,s.byteOffset+s.byteLength);return new Uint8Array(i)}function ia(s){let i=s._queue.shift();return s._queueTotalSize-=i.size,s._queueTotalSize<0&&(s._queueTotalSize=0),i.value}function aa(s,i,c){if(!lg(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");s._queue.push({value:i,size:c}),s._queueTotalSize+=c}function fg(s){return s._queue.peek().value}function Cr(s){s._queue=new j,s._queueTotalSize=0}function Dl(s){return s===DataView}function dg(s){return Dl(s.constructor)}function hg(s){return Dl(s)?1:s.BYTES_PER_ELEMENT}class jr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!ua(this))throw ha("view");return this._view}respond(i){if(!ua(this))throw ha("respond");if(Ne(i,1,"respond"),i=T(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(_r(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ms(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!ua(this))throw ha("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(_r(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");$s(this._associatedReadableByteStreamController,i)}}Object.defineProperties(jr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(jr.prototype.respond,"respond"),o(jr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class nr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Lr(this))throw Xn("byobRequest");return da(this)}get desiredSize(){if(!Lr(this))throw Xn("desiredSize");return Bl(this)}close(){if(!Lr(this))throw Xn("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);Yn(this)}enqueue(i){if(!Lr(this))throw Xn("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);Us(this,i)}error(i=void 0){if(!Lr(this))throw Xn("error");Ct(this,i)}[K](i){Sl(this),Cr(this);let c=this._cancelAlgorithm(i);return Ls(this),c}[W](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){xl(this,i);return}let m=this._autoAllocateChunkSize;if(m!==void 0){let A;try{A=new ArrayBuffer(m)}catch(U){i._errorSteps(U);return}let I={buffer:A,bufferByteLength:m,byteOffset:0,byteLength:m,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(I)}D(c,i),Ur(this)}[Ae](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new j,this._pendingPullIntos.push(i)}}}Object.defineProperties(nr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(nr.prototype.close,"close"),o(nr.prototype.enqueue,"enqueue"),o(nr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Lr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableByteStream")?!1:s instanceof nr}function ua(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_associatedReadableByteStreamController")?!1:s instanceof jr}function Ur(s){if(!_g(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,Ur(s)),null),m=>(Ct(s,m),null))}function Sl(s){la(s),s._pendingPullIntos=new j}function ca(s,i){let c=!1;s._state==="closed"&&(c=!0);let m=vl(i);i.readerType==="default"?k(s,m,c):Dg(s,m,c)}function vl(s){let i=s.bytesFilled,c=s.elementSize;return new s.viewConstructor(s.buffer,s.byteOffset,i/c)}function js(s,i,c,m){s._queue.push({buffer:i,byteOffset:c,byteLength:m}),s._queueTotalSize+=m}function Tl(s,i,c,m){let A;try{A=El(i,c,c+m)}catch(I){throw Ct(s,I),I}js(s,A,0,m)}function Rl(s,i){i.bytesFilled>0&&Tl(s,i.buffer,i.byteOffset,i.bytesFilled),un(s)}function kl(s,i){let c=Math.min(s._queueTotalSize,i.byteLength-i.bytesFilled),m=i.bytesFilled+c,A=c,I=!1,U=m%i.elementSize,V=m-U;V>=i.minimumFill&&(A=V-i.bytesFilled,I=!0);let ae=s._queue;for(;A>0;){let te=ae.peek(),ce=Math.min(A,te.byteLength),ge=i.byteOffset+i.bytesFilled;bl(i.buffer,ge,te.buffer,te.byteOffset,ce),te.byteLength===ce?ae.shift():(te.byteOffset+=ce,te.byteLength-=ce),s._queueTotalSize-=ce,Fl(s,ce,i),A-=ce}return I}function Fl(s,i,c){c.bytesFilled+=i}function Ol(s){s._queueTotalSize===0&&s._closeRequested?(Ls(s),ns(s._controlledReadableByteStream)):Ur(s)}function la(s){s._byobRequest!==null&&(s._byobRequest._associatedReadableByteStreamController=void 0,s._byobRequest._view=null,s._byobRequest=null)}function fa(s){for(;s._pendingPullIntos.length>0;){if(s._queueTotalSize===0)return;let i=s._pendingPullIntos.peek();kl(s,i)&&(un(s),ca(s._controlledReadableByteStream,i))}}function pg(s){let i=s._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(s._queueTotalSize===0)return;let c=i._readRequests.shift();xl(s,c)}}function mg(s,i,c,m){let A=s._controlledReadableByteStream,I=i.constructor,U=hg(I),{byteOffset:V,byteLength:ae}=i,te=c*U,ce;try{ce=rr(i.buffer)}catch(Te){m._errorSteps(Te);return}let ge={buffer:ce,bufferByteLength:ce.byteLength,byteOffset:V,byteLength:ae,bytesFilled:0,minimumFill:te,elementSize:U,viewConstructor:I,readerType:"byob"};if(s._pendingPullIntos.length>0){s._pendingPullIntos.push(ge),ql(A,m);return}if(A._state==="closed"){let Te=new I(ge.buffer,ge.byteOffset,0);m._closeSteps(Te);return}if(s._queueTotalSize>0){if(kl(s,ge)){let Te=vl(ge);Ol(s),m._chunkSteps(Te);return}if(s._closeRequested){let Te=new TypeError("Insufficient bytes to fill elements in the given buffer");Ct(s,Te),m._errorSteps(Te);return}}s._pendingPullIntos.push(ge),ql(A,m),Ur(s)}function gg(s,i){i.readerType==="none"&&un(s);let c=s._controlledReadableByteStream;if(pa(c))for(;jl(c)>0;){let m=un(s);ca(c,m)}}function yg(s,i,c){if(Fl(s,i,c),c.readerType==="none"){Rl(s,c),fa(s);return}if(c.bytesFilled0){let A=c.byteOffset+c.bytesFilled;Tl(s,c.buffer,A-m,m)}c.bytesFilled-=m,ca(s._controlledReadableByteStream,c),fa(s)}function Pl(s,i){let c=s._pendingPullIntos.peek();la(s),s._controlledReadableByteStream._state==="closed"?gg(s,c):yg(s,i,c),Ur(s)}function un(s){return s._pendingPullIntos.shift()}function _g(s){let i=s._controlledReadableByteStream;return i._state!=="readable"||s._closeRequested||!s._started?!1:!!(O(i)&&B(i)>0||pa(i)&&jl(i)>0||Bl(s)>0)}function Ls(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0}function Yn(s){let i=s._controlledReadableByteStream;if(!(s._closeRequested||i._state!=="readable")){if(s._queueTotalSize>0){s._closeRequested=!0;return}if(s._pendingPullIntos.length>0){let c=s._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let m=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ct(s,m),m}}Ls(s),ns(i)}}function Us(s,i){let c=s._controlledReadableByteStream;if(s._closeRequested||c._state!=="readable")return;let{buffer:m,byteOffset:A,byteLength:I}=i;if(_r(m))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let U=rr(m);if(s._pendingPullIntos.length>0){let V=s._pendingPullIntos.peek();if(_r(V.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");la(s),V.buffer=rr(V.buffer),V.readerType==="none"&&Rl(s,V)}if(O(c))if(pg(s),B(c)===0)js(s,U,A,I);else{s._pendingPullIntos.length>0&&un(s);let V=new Uint8Array(U,A,I);k(c,V,!1)}else pa(c)?(js(s,U,A,I),fa(s)):js(s,U,A,I);Ur(s)}function Ct(s,i){let c=s._controlledReadableByteStream;c._state==="readable"&&(Sl(s),Cr(s),Ls(s),cf(c,i))}function xl(s,i){let c=s._queue.shift();s._queueTotalSize-=c.byteLength,Ol(s);let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(m)}function da(s){if(s._byobRequest===null&&s._pendingPullIntos.length>0){let i=s._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),m=Object.create(jr.prototype);bg(m,s,c),s._byobRequest=m}return s._byobRequest}function Bl(s){let i=s._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function Ms(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=rr(c.buffer),Pl(s,i)}function $s(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let A=i.byteLength;c.buffer=rr(i.buffer),Pl(s,A)}function Il(s,i,c,m,A,I,U){i._controlledReadableByteStream=s,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Cr(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,i._autoAllocateChunkSize=U,i._pendingPullIntos=new j,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,Ur(i),null),ae=>(Ct(i,ae),null))}function Cg(s,i,c){let m=Object.create(nr.prototype),A,I,U;i.start!==void 0?A=()=>i.start(m):A=()=>{},i.pull!==void 0?I=()=>i.pull(m):I=()=>h(void 0),i.cancel!==void 0?U=ae=>i.cancel(ae):U=()=>h(void 0);let V=i.autoAllocateChunkSize;if(V===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Il(s,m,A,I,U,c,V)}function bg(s,i,c){s._associatedReadableByteStreamController=i,s._view=c}function ha(s){return new TypeError(`ReadableStreamBYOBRequest.prototype.${s} can only be used on a ReadableStreamBYOBRequest`)}function Xn(s){return new TypeError(`ReadableByteStreamController.prototype.${s} can only be used on a ReadableByteStreamController`)}function Eg(s,i){pe(s,i);let c=s?.mode;return{mode:c===void 0?void 0:wg(c,`${i} has member 'mode' that`)}}function wg(s,i){if(s=`${s}`,s!=="byob")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamReaderMode`);return s}function Ag(s,i){var c;pe(s,i);let m=(c=s?.min)!==null&&c!==void 0?c:1;return{min:T(m,`${i} has member 'min' that`)}}function Nl(s){return new br(s)}function ql(s,i){s._reader._readIntoRequests.push(i)}function Dg(s,i,c){let A=s._reader._readIntoRequests.shift();c?A._closeSteps(i):A._chunkSteps(i)}function jl(s){return s._reader._readIntoRequests.length}function pa(s){let i=s._reader;return!(i===void 0||!Mr(i))}class br{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),F(i,"First parameter"),Ar(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Lr(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");he(this,i),this._readIntoRequests=new j}get closed(){return Mr(this)?this._closedPromise:d(Hs("closed"))}cancel(i=void 0){return Mr(this)?this._ownerReadableStream===void 0?d(re("cancel")):fe(this,i):d(Hs("cancel"))}read(i,c={}){if(!Mr(this))return d(Hs("read"));if(!ArrayBuffer.isView(i))return d(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(_r(i.buffer))return d(new TypeError("view's buffer has been detached"));let m;try{m=Ag(c,"options")}catch(te){return d(te)}let A=m.min;if(A===0)return d(new TypeError("options.min must be greater than 0"));if(dg(i)){if(A>i.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(A>i.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(re("read from"));let I,U,V=f((te,ce)=>{I=te,U=ce});return Ll(this,i,A,{_chunkSteps:te=>I({value:te,done:!1}),_closeSteps:te=>I({value:te,done:!0}),_errorSteps:te=>U(te)}),V}releaseLock(){if(!Mr(this))throw Hs("releaseLock");this._ownerReadableStream!==void 0&&Sg(this)}}Object.defineProperties(br.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(br.prototype.cancel,"cancel"),o(br.prototype.read,"read"),o(br.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(br.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Mr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readIntoRequests")?!1:s instanceof br}function Ll(s,i,c,m){let A=s._ownerReadableStream;A._disturbed=!0,A._state==="errored"?m._errorSteps(A._storedError):mg(A._readableStreamController,i,c,m)}function Sg(s){ye(s);let i=new TypeError("Reader was released");Ul(s,i)}function Ul(s,i){let c=s._readIntoRequests;s._readIntoRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function Hs(s){return new TypeError(`ReadableStreamBYOBReader.prototype.${s} can only be used on a ReadableStreamBYOBReader`)}function Qn(s,i){let{highWaterMark:c}=s;if(c===void 0)return i;if(ut(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Gs(s){let{size:i}=s;return i||(()=>1)}function Ws(s,i){pe(s,i);let c=s?.highWaterMark,m=s?.size;return{highWaterMark:c===void 0?void 0:y(c),size:m===void 0?void 0:vg(m,`${i} has member 'size' that`)}}function vg(s,i){return Ee(s,i),c=>y(s(c))}function Tg(s,i){pe(s,i);let c=s?.abort,m=s?.close,A=s?.start,I=s?.type,U=s?.write;return{abort:c===void 0?void 0:Rg(c,s,`${i} has member 'abort' that`),close:m===void 0?void 0:kg(m,s,`${i} has member 'close' that`),start:A===void 0?void 0:Fg(A,s,`${i} has member 'start' that`),write:U===void 0?void 0:Og(U,s,`${i} has member 'write' that`),type:I}}function Rg(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function kg(s,i,c){return Ee(s,c),()=>S(s,i,[])}function Fg(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function Og(s,i,c){return Ee(s,c),(m,A)=>S(s,i,[m,A])}function Ml(s,i){if(!cn(s))throw new TypeError(`${i} is not a WritableStream.`)}function Pg(s){if(typeof s!="object"||s===null)return!1;try{return typeof s.aborted=="boolean"}catch{return!1}}let xg=typeof AbortController=="function";function Bg(){if(xg)return new AbortController}class Er{constructor(i={},c={}){i===void 0?i=null:xe(i,"First parameter");let m=Ws(c,"Second parameter"),A=Tg(i,"First parameter");if(Hl(this),A.type!==void 0)throw new RangeError("Invalid type is specified");let U=Gs(m),V=Qn(m,1);Vg(this,A,V,U)}get locked(){if(!cn(this))throw Ys("locked");return ln(this)}abort(i=void 0){return cn(this)?ln(this)?d(new TypeError("Cannot abort a stream that already has a writer")):zs(this,i):d(Ys("abort"))}close(){return cn(this)?ln(this)?d(new TypeError("Cannot close a stream that already has a writer")):Ht(this)?d(new TypeError("Cannot close an already-closing stream")):Gl(this):d(Ys("close"))}getWriter(){if(!cn(this))throw Ys("getWriter");return $l(this)}}Object.defineProperties(Er.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Er.prototype.abort,"abort"),o(Er.prototype.close,"close"),o(Er.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Er.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function $l(s){return new sr(s)}function Ig(s,i,c,m,A=1,I=()=>1){let U=Object.create(Er.prototype);Hl(U);let V=Object.create(fn.prototype);return Yl(U,V,s,i,c,m,A,I),U}function Hl(s){s._state="writable",s._storedError=void 0,s._writer=void 0,s._writableStreamController=void 0,s._writeRequests=new j,s._inFlightWriteRequest=void 0,s._closeRequest=void 0,s._inFlightCloseRequest=void 0,s._pendingAbortRequest=void 0,s._backpressure=!1}function cn(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_writableStreamController")?!1:s instanceof Er}function ln(s){return s._writer!==void 0}function zs(s,i){var c;if(s._state==="closed"||s._state==="errored")return h(void 0);s._writableStreamController._abortReason=i,(c=s._writableStreamController._abortController)===null||c===void 0||c.abort(i);let m=s._state;if(m==="closed"||m==="errored")return h(void 0);if(s._pendingAbortRequest!==void 0)return s._pendingAbortRequest._promise;let A=!1;m==="erroring"&&(A=!0,i=void 0);let I=f((U,V)=>{s._pendingAbortRequest={_promise:void 0,_resolve:U,_reject:V,_reason:i,_wasAlreadyErroring:A}});return s._pendingAbortRequest._promise=I,A||ga(s,i),I}function Gl(s){let i=s._state;if(i==="closed"||i==="errored")return d(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=f((A,I)=>{let U={_resolve:A,_reject:I};s._closeRequest=U}),m=s._writer;return m!==void 0&&s._backpressure&&i==="writable"&&Da(m),Kg(s._writableStreamController),c}function Ng(s){return f((c,m)=>{let A={_resolve:c,_reject:m};s._writeRequests.push(A)})}function ma(s,i){if(s._state==="writable"){ga(s,i);return}ya(s)}function ga(s,i){let c=s._writableStreamController;s._state="erroring",s._storedError=i;let m=s._writer;m!==void 0&&zl(m,i),!Mg(s)&&c._started&&ya(s)}function ya(s){s._state="errored",s._writableStreamController[H]();let i=s._storedError;if(s._writeRequests.forEach(A=>{A._reject(i)}),s._writeRequests=new j,s._pendingAbortRequest===void 0){Js(s);return}let c=s._pendingAbortRequest;if(s._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Js(s);return}let m=s._writableStreamController[L](c._reason);E(m,()=>(c._resolve(),Js(s),null),A=>(c._reject(A),Js(s),null))}function qg(s){s._inFlightWriteRequest._resolve(void 0),s._inFlightWriteRequest=void 0}function jg(s,i){s._inFlightWriteRequest._reject(i),s._inFlightWriteRequest=void 0,ma(s,i)}function Lg(s){s._inFlightCloseRequest._resolve(void 0),s._inFlightCloseRequest=void 0,s._state==="erroring"&&(s._storedError=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._resolve(),s._pendingAbortRequest=void 0)),s._state="closed";let c=s._writer;c!==void 0&&ef(c)}function Ug(s,i){s._inFlightCloseRequest._reject(i),s._inFlightCloseRequest=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._reject(i),s._pendingAbortRequest=void 0),ma(s,i)}function Ht(s){return!(s._closeRequest===void 0&&s._inFlightCloseRequest===void 0)}function Mg(s){return!(s._inFlightWriteRequest===void 0&&s._inFlightCloseRequest===void 0)}function $g(s){s._inFlightCloseRequest=s._closeRequest,s._closeRequest=void 0}function Hg(s){s._inFlightWriteRequest=s._writeRequests.shift()}function Js(s){s._closeRequest!==void 0&&(s._closeRequest._reject(s._storedError),s._closeRequest=void 0);let i=s._writer;i!==void 0&&wa(i,s._storedError)}function _a(s,i){let c=s._writer;c!==void 0&&i!==s._backpressure&&(i?ry(c):Da(c)),s._backpressure=i}class sr{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),Ml(i,"First parameter"),ln(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ht(i)&&i._backpressure?Qs(this):tf(this),Xs(this);else if(c==="erroring")Aa(this,i._storedError),Xs(this);else if(c==="closed")tf(this),ey(this);else{let m=i._storedError;Aa(this,m),Zl(this,m)}}get closed(){return $r(this)?this._closedPromise:d(Hr("closed"))}get desiredSize(){if(!$r(this))throw Hr("desiredSize");if(this._ownerWritableStream===void 0)throw es("desiredSize");return Jg(this)}get ready(){return $r(this)?this._readyPromise:d(Hr("ready"))}abort(i=void 0){return $r(this)?this._ownerWritableStream===void 0?d(es("abort")):Gg(this,i):d(Hr("abort"))}close(){if(!$r(this))return d(Hr("close"));let i=this._ownerWritableStream;return i===void 0?d(es("close")):Ht(i)?d(new TypeError("Cannot close an already-closing stream")):Wl(this)}releaseLock(){if(!$r(this))throw Hr("releaseLock");this._ownerWritableStream!==void 0&&Jl(this)}write(i=void 0){return $r(this)?this._ownerWritableStream===void 0?d(es("write to")):Vl(this,i):d(Hr("write"))}}Object.defineProperties(sr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(sr.prototype.abort,"abort"),o(sr.prototype.close,"close"),o(sr.prototype.releaseLock,"releaseLock"),o(sr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function $r(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_ownerWritableStream")?!1:s instanceof sr}function Gg(s,i){let c=s._ownerWritableStream;return zs(c,i)}function Wl(s){let i=s._ownerWritableStream;return Gl(i)}function Wg(s){let i=s._ownerWritableStream,c=i._state;return Ht(i)||c==="closed"?h(void 0):c==="errored"?d(i._storedError):Wl(s)}function zg(s,i){s._closedPromiseState==="pending"?wa(s,i):ty(s,i)}function zl(s,i){s._readyPromiseState==="pending"?rf(s,i):ny(s,i)}function Jg(s){let i=s._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Xl(i._writableStreamController)}function Jl(s){let i=s._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zl(s,c),zg(s,c),i._writer=void 0,s._ownerWritableStream=void 0}function Vl(s,i){let c=s._ownerWritableStream,m=c._writableStreamController,A=Yg(m,i);if(c!==s._ownerWritableStream)return d(es("write to"));let I=c._state;if(I==="errored")return d(c._storedError);if(Ht(c)||I==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(I==="erroring")return d(c._storedError);let U=Ng(c);return Xg(m,i,A),U}let Kl={};class fn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ca(this))throw Ea("abortReason");return this._abortReason}get signal(){if(!Ca(this))throw Ea("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Ca(this))throw Ea("error");this._controlledWritableStream._state==="writable"&&Ql(this,i)}[L](i){let c=this._abortAlgorithm(i);return Vs(this),c}[H](){Cr(this)}}Object.defineProperties(fn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Ca(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledWritableStream")?!1:s instanceof fn}function Yl(s,i,c,m,A,I,U,V){i._controlledWritableStream=s,s._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Cr(i),i._abortReason=void 0,i._abortController=Bg(),i._started=!1,i._strategySizeAlgorithm=V,i._strategyHWM=U,i._writeAlgorithm=m,i._closeAlgorithm=A,i._abortAlgorithm=I;let ae=ba(i);_a(s,ae);let te=c(),ce=h(te);E(ce,()=>(i._started=!0,Ks(i),null),ge=>(i._started=!0,ma(s,ge),null))}function Vg(s,i,c,m){let A=Object.create(fn.prototype),I,U,V,ae;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.write!==void 0?U=te=>i.write(te,A):U=()=>h(void 0),i.close!==void 0?V=()=>i.close():V=()=>h(void 0),i.abort!==void 0?ae=te=>i.abort(te):ae=()=>h(void 0),Yl(s,A,I,U,V,ae,c,m)}function Vs(s){s._writeAlgorithm=void 0,s._closeAlgorithm=void 0,s._abortAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function Kg(s){aa(s,Kl,0),Ks(s)}function Yg(s,i){try{return s._strategySizeAlgorithm(i)}catch(c){return Zn(s,c),1}}function Xl(s){return s._strategyHWM-s._queueTotalSize}function Xg(s,i,c){try{aa(s,i,c)}catch(A){Zn(s,A);return}let m=s._controlledWritableStream;if(!Ht(m)&&m._state==="writable"){let A=ba(s);_a(m,A)}Ks(s)}function Ks(s){let i=s._controlledWritableStream;if(!s._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){ya(i);return}if(s._queue.length===0)return;let m=fg(s);m===Kl?Qg(s):Zg(s,m)}function Zn(s,i){s._controlledWritableStream._state==="writable"&&Ql(s,i)}function Qg(s){let i=s._controlledWritableStream;$g(i),ia(s);let c=s._closeAlgorithm();Vs(s),E(c,()=>(Lg(i),null),m=>(Ug(i,m),null))}function Zg(s,i){let c=s._controlledWritableStream;Hg(c);let m=s._writeAlgorithm(i);E(m,()=>{qg(c);let A=c._state;if(ia(s),!Ht(c)&&A==="writable"){let I=ba(s);_a(c,I)}return Ks(s),null},A=>(c._state==="writable"&&Vs(s),jg(c,A),null))}function ba(s){return Xl(s)<=0}function Ql(s,i){let c=s._controlledWritableStream;Vs(s),ga(c,i)}function Ys(s){return new TypeError(`WritableStream.prototype.${s} can only be used on a WritableStream`)}function Ea(s){return new TypeError(`WritableStreamDefaultController.prototype.${s} can only be used on a WritableStreamDefaultController`)}function Hr(s){return new TypeError(`WritableStreamDefaultWriter.prototype.${s} can only be used on a WritableStreamDefaultWriter`)}function es(s){return new TypeError("Cannot "+s+" a stream using a released writer")}function Xs(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c,s._closedPromiseState="pending"})}function Zl(s,i){Xs(s),wa(s,i)}function ey(s){Xs(s),ef(s)}function wa(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="rejected")}function ty(s,i){Zl(s,i)}function ef(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="resolved")}function Qs(s){s._readyPromise=f((i,c)=>{s._readyPromise_resolve=i,s._readyPromise_reject=c}),s._readyPromiseState="pending"}function Aa(s,i){Qs(s),rf(s,i)}function tf(s){Qs(s),Da(s)}function rf(s,i){s._readyPromise_reject!==void 0&&(g(s._readyPromise),s._readyPromise_reject(i),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="rejected")}function ry(s){Qs(s)}function ny(s,i){Aa(s,i)}function Da(s){s._readyPromise_resolve!==void 0&&(s._readyPromise_resolve(void 0),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="fulfilled")}function sy(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Sa=sy();function oy(s){if(!(typeof s=="function"||typeof s=="object")||s.name!=="DOMException")return!1;try{return new s,!0}catch{return!1}}function iy(){let s=Sa?.DOMException;return oy(s)?s:void 0}function ay(){let s=function(c,m){this.message=c||"",this.name=m||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(s,"DOMException"),s.prototype=Object.create(Error.prototype),Object.defineProperty(s.prototype,"constructor",{value:s,writable:!0,configurable:!0}),s}let uy=iy()||ay();function nf(s,i,c,m,A,I){let U=q(s),V=$l(i);s._disturbed=!0;let ae=!1,te=h(void 0);return f((ce,ge)=>{let Te;if(I!==void 0){if(Te=()=>{let ne=I.reason!==void 0?I.reason:new uy("Aborted","AbortError"),_e=[];m||_e.push(()=>i._state==="writable"?zs(i,ne):h(void 0)),A||_e.push(()=>s._state==="readable"?Ft(s,ne):h(void 0)),rt(()=>Promise.all(_e.map(Re=>Re())),!0,ne)},I.aborted){Te();return}I.addEventListener("abort",Te)}function Ot(){return f((ne,_e)=>{function Re(ct){ct?ne():_(mn(),Re,_e)}Re(!1)})}function mn(){return ae?h(!0):_(V._readyPromise,()=>f((ne,_e)=>{Q(U,{_chunkSteps:Re=>{te=_(Vl(V,Re),void 0,e),ne(!1)},_closeSteps:()=>ne(!0),_errorSteps:_e})}))}if(ir(s,U._closedPromise,ne=>(m?bt(!0,ne):rt(()=>zs(i,ne),!0,ne),null)),ir(i,V._closedPromise,ne=>(A?bt(!0,ne):rt(()=>Ft(s,ne),!0,ne),null)),Qe(s,U._closedPromise,()=>(c?bt():rt(()=>Wg(V)),null)),Ht(i)||i._state==="closed"){let ne=new TypeError("the destination writable stream closed before all data could be piped to it");A?bt(!0,ne):rt(()=>Ft(s,ne),!0,ne)}g(Ot());function Sr(){let ne=te;return _(te,()=>ne!==te?Sr():void 0)}function ir(ne,_e,Re){ne._state==="errored"?Re(ne._storedError):v(_e,Re)}function Qe(ne,_e,Re){ne._state==="closed"?Re():P(_e,Re)}function rt(ne,_e,Re){if(ae)return;ae=!0,i._state==="writable"&&!Ht(i)?P(Sr(),ct):ct();function ct(){return E(ne(),()=>ar(_e,Re),gn=>ar(!0,gn)),null}}function bt(ne,_e){ae||(ae=!0,i._state==="writable"&&!Ht(i)?P(Sr(),()=>ar(ne,_e)):ar(ne,_e))}function ar(ne,_e){return Jl(V),ye(U),I!==void 0&&I.removeEventListener("abort",Te),ne?ge(_e):ce(void 0),null}})}class or{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Zs(this))throw to("desiredSize");return va(this)}close(){if(!Zs(this))throw to("close");if(!hn(this))throw new TypeError("The stream is not in a state that permits close");Gr(this)}enqueue(i=void 0){if(!Zs(this))throw to("enqueue");if(!hn(this))throw new TypeError("The stream is not in a state that permits enqueue");return dn(this,i)}error(i=void 0){if(!Zs(this))throw to("error");kt(this,i)}[K](i){Cr(this);let c=this._cancelAlgorithm(i);return eo(this),c}[W](i){let c=this._controlledReadableStream;if(this._queue.length>0){let m=ia(this);this._closeRequested&&this._queue.length===0?(eo(this),ns(c)):ts(this),i._chunkSteps(m)}else D(c,i),ts(this)}[Ae](){}}Object.defineProperties(or.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(or.prototype.close,"close"),o(or.prototype.enqueue,"enqueue"),o(or.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Zs(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableStream")?!1:s instanceof or}function ts(s){if(!sf(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,ts(s)),null),m=>(kt(s,m),null))}function sf(s){let i=s._controlledReadableStream;return!hn(s)||!s._started?!1:!!(Ar(i)&&B(i)>0||va(s)>0)}function eo(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function Gr(s){if(!hn(s))return;let i=s._controlledReadableStream;s._closeRequested=!0,s._queue.length===0&&(eo(s),ns(i))}function dn(s,i){if(!hn(s))return;let c=s._controlledReadableStream;if(Ar(c)&&B(c)>0)k(c,i,!1);else{let m;try{m=s._strategySizeAlgorithm(i)}catch(A){throw kt(s,A),A}try{aa(s,i,m)}catch(A){throw kt(s,A),A}}ts(s)}function kt(s,i){let c=s._controlledReadableStream;c._state==="readable"&&(Cr(s),eo(s),cf(c,i))}function va(s){let i=s._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function cy(s){return!sf(s)}function hn(s){let i=s._controlledReadableStream._state;return!s._closeRequested&&i==="readable"}function of(s,i,c,m,A,I,U){i._controlledReadableStream=s,i._queue=void 0,i._queueTotalSize=void 0,Cr(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=U,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,ts(i),null),ae=>(kt(i,ae),null))}function ly(s,i,c,m){let A=Object.create(or.prototype),I,U,V;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.pull!==void 0?U=()=>i.pull(A):U=()=>h(void 0),i.cancel!==void 0?V=ae=>i.cancel(ae):V=()=>h(void 0),of(s,A,I,U,V,c,m)}function to(s){return new TypeError(`ReadableStreamDefaultController.prototype.${s} can only be used on a ReadableStreamDefaultController`)}function fy(s,i){return Lr(s._readableStreamController)?hy(s):dy(s)}function dy(s,i){let c=q(s),m=!1,A=!1,I=!1,U=!1,V,ae,te,ce,ge,Te=f(Qe=>{ge=Qe});function Ot(){return m?(A=!0,h(void 0)):(m=!0,Q(c,{_chunkSteps:rt=>{C(()=>{A=!1;let bt=rt,ar=rt;I||dn(te._readableStreamController,bt),U||dn(ce._readableStreamController,ar),m=!1,A&&Ot()})},_closeSteps:()=>{m=!1,I||Gr(te._readableStreamController),U||Gr(ce._readableStreamController),(!I||!U)&&ge(void 0)},_errorSteps:()=>{m=!1}}),h(void 0))}function mn(Qe){if(I=!0,V=Qe,U){let rt=Se([V,ae]),bt=Ft(s,rt);ge(bt)}return Te}function Sr(Qe){if(U=!0,ae=Qe,I){let rt=Se([V,ae]),bt=Ft(s,rt);ge(bt)}return Te}function ir(){}return te=rs(ir,Ot,mn),ce=rs(ir,Ot,Sr),v(c._closedPromise,Qe=>(kt(te._readableStreamController,Qe),kt(ce._readableStreamController,Qe),(!I||!U)&&ge(void 0),null)),[te,ce]}function hy(s){let i=q(s),c=!1,m=!1,A=!1,I=!1,U=!1,V,ae,te,ce,ge,Te=f(ne=>{ge=ne});function Ot(ne){v(ne._closedPromise,_e=>(ne!==i||(Ct(te._readableStreamController,_e),Ct(ce._readableStreamController,_e),(!I||!U)&&ge(void 0)),null))}function mn(){Mr(i)&&(ye(i),i=q(s),Ot(i)),Q(i,{_chunkSteps:_e=>{C(()=>{m=!1,A=!1;let Re=_e,ct=_e;if(!I&&!U)try{ct=Al(_e)}catch(gn){Ct(te._readableStreamController,gn),Ct(ce._readableStreamController,gn),ge(Ft(s,gn));return}I||Us(te._readableStreamController,Re),U||Us(ce._readableStreamController,ct),c=!1,m?ir():A&&Qe()})},_closeSteps:()=>{c=!1,I||Yn(te._readableStreamController),U||Yn(ce._readableStreamController),te._readableStreamController._pendingPullIntos.length>0&&Ms(te._readableStreamController,0),ce._readableStreamController._pendingPullIntos.length>0&&Ms(ce._readableStreamController,0),(!I||!U)&&ge(void 0)},_errorSteps:()=>{c=!1}})}function Sr(ne,_e){Y(i)&&(ye(i),i=Nl(s),Ot(i));let Re=_e?ce:te,ct=_e?te:ce;Ll(i,ne,1,{_chunkSteps:yn=>{C(()=>{m=!1,A=!1;let _n=_e?U:I;if(_e?I:U)_n||$s(Re._readableStreamController,yn);else{let wf;try{wf=Al(yn)}catch(Oa){Ct(Re._readableStreamController,Oa),Ct(ct._readableStreamController,Oa),ge(Ft(s,Oa));return}_n||$s(Re._readableStreamController,yn),Us(ct._readableStreamController,wf)}c=!1,m?ir():A&&Qe()})},_closeSteps:yn=>{c=!1;let _n=_e?U:I,co=_e?I:U;_n||Yn(Re._readableStreamController),co||Yn(ct._readableStreamController),yn!==void 0&&(_n||$s(Re._readableStreamController,yn),!co&&ct._readableStreamController._pendingPullIntos.length>0&&Ms(ct._readableStreamController,0)),(!_n||!co)&&ge(void 0)},_errorSteps:()=>{c=!1}})}function ir(){if(c)return m=!0,h(void 0);c=!0;let ne=da(te._readableStreamController);return ne===null?mn():Sr(ne._view,!1),h(void 0)}function Qe(){if(c)return A=!0,h(void 0);c=!0;let ne=da(ce._readableStreamController);return ne===null?mn():Sr(ne._view,!0),h(void 0)}function rt(ne){if(I=!0,V=ne,U){let _e=Se([V,ae]),Re=Ft(s,_e);ge(Re)}return Te}function bt(ne){if(U=!0,ae=ne,I){let _e=Se([V,ae]),Re=Ft(s,_e);ge(Re)}return Te}function ar(){}return te=uf(ar,ir,rt),ce=uf(ar,Qe,bt),Ot(i),[te,ce]}function py(s){return t(s)&&typeof s.getReader<"u"}function my(s){return py(s)?yy(s.getReader()):gy(s)}function gy(s){let i,c=wl(s,"async"),m=e;function A(){let U;try{U=ag(c)}catch(ae){return d(ae)}let V=h(U);return w(V,ae=>{if(!t(ae))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(ug(ae))Gr(i._readableStreamController);else{let ce=cg(ae);dn(i._readableStreamController,ce)}})}function I(U){let V=c.iterator,ae;try{ae=qs(V,"return")}catch(ge){return d(ge)}if(ae===void 0)return h(void 0);let te;try{te=R(ae,V,[U])}catch(ge){return d(ge)}let ce=h(te);return w(ce,ge=>{if(!t(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=rs(m,A,I,0),i}function yy(s){let i,c=e;function m(){let I;try{I=s.read()}catch(U){return d(U)}return w(I,U=>{if(!t(U))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(U.done)Gr(i._readableStreamController);else{let V=U.value;dn(i._readableStreamController,V)}})}function A(I){try{return h(s.cancel(I))}catch(U){return d(U)}}return i=rs(c,m,A,0),i}function _y(s,i){pe(s,i);let c=s,m=c?.autoAllocateChunkSize,A=c?.cancel,I=c?.pull,U=c?.start,V=c?.type;return{autoAllocateChunkSize:m===void 0?void 0:T(m,`${i} has member 'autoAllocateChunkSize' that`),cancel:A===void 0?void 0:Cy(A,c,`${i} has member 'cancel' that`),pull:I===void 0?void 0:by(I,c,`${i} has member 'pull' that`),start:U===void 0?void 0:Ey(U,c,`${i} has member 'start' that`),type:V===void 0?void 0:wy(V,`${i} has member 'type' that`)}}function Cy(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function by(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function Ey(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function wy(s,i){if(s=`${s}`,s!=="bytes")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamType`);return s}function Ay(s,i){return pe(s,i),{preventCancel:!!s?.preventCancel}}function af(s,i){pe(s,i);let c=s?.preventAbort,m=s?.preventCancel,A=s?.preventClose,I=s?.signal;return I!==void 0&&Dy(I,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!m,preventClose:!!A,signal:I}}function Dy(s,i){if(!Pg(s))throw new TypeError(`${i} is not an AbortSignal.`)}function Sy(s,i){pe(s,i);let c=s?.readable;p(c,"readable","ReadableWritablePair"),F(c,`${i} has member 'readable' that`);let m=s?.writable;return p(m,"writable","ReadableWritablePair"),Ml(m,`${i} has member 'writable' that`),{readable:c,writable:m}}class Ke{constructor(i={},c={}){i===void 0?i=null:xe(i,"First parameter");let m=Ws(c,"Second parameter"),A=_y(i,"First parameter");if(Ta(this),A.type==="bytes"){if(m.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let I=Qn(m,0);Cg(this,A,I)}else{let I=Gs(m),U=Qn(m,1);ly(this,A,U,I)}}get locked(){if(!wr(this))throw Wr("locked");return Ar(this)}cancel(i=void 0){return wr(this)?Ar(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Ft(this,i):d(Wr("cancel"))}getReader(i=void 0){if(!wr(this))throw Wr("getReader");return Eg(i,"First parameter").mode===void 0?q(this):Nl(this)}pipeThrough(i,c={}){if(!wr(this))throw Wr("pipeThrough");Ne(i,1,"pipeThrough");let m=Sy(i,"First parameter"),A=af(c,"Second parameter");if(Ar(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(ln(m.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let I=nf(this,m.writable,A.preventClose,A.preventAbort,A.preventCancel,A.signal);return g(I),m.readable}pipeTo(i,c={}){if(!wr(this))return d(Wr("pipeTo"));if(i===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!cn(i))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let m;try{m=af(c,"Second parameter")}catch(A){return d(A)}return Ar(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):ln(i)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):nf(this,i,m.preventClose,m.preventAbort,m.preventCancel,m.signal)}tee(){if(!wr(this))throw Wr("tee");let i=fy(this);return Se(i)}values(i=void 0){if(!wr(this))throw Wr("values");let c=Ay(i,"First parameter");return sn(this,c.preventCancel)}[oa](i){return this.values(i)}static from(i){return my(i)}}Object.defineProperties(Ke,{from:{enumerable:!0}}),Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Ke.from,"from"),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.getReader,"getReader"),o(Ke.prototype.pipeThrough,"pipeThrough"),o(Ke.prototype.pipeTo,"pipeTo"),o(Ke.prototype.tee,"tee"),o(Ke.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ke.prototype,oa,{value:Ke.prototype.values,writable:!0,configurable:!0});function rs(s,i,c,m=1,A=()=>1){let I=Object.create(Ke.prototype);Ta(I);let U=Object.create(or.prototype);return of(I,U,s,i,c,m,A),I}function uf(s,i,c){let m=Object.create(Ke.prototype);Ta(m);let A=Object.create(nr.prototype);return Il(m,A,s,i,c,0,void 0),m}function Ta(s){s._state="readable",s._reader=void 0,s._storedError=void 0,s._disturbed=!1}function wr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readableStreamController")?!1:s instanceof Ke}function Ar(s){return s._reader!==void 0}function Ft(s,i){if(s._disturbed=!0,s._state==="closed")return h(void 0);if(s._state==="errored")return d(s._storedError);ns(s);let c=s._reader;if(c!==void 0&&Mr(c)){let A=c._readIntoRequests;c._readIntoRequests=new j,A.forEach(I=>{I._closeSteps(void 0)})}let m=s._readableStreamController[K](i);return w(m,e)}function ns(s){s._state="closed";let i=s._reader;if(i!==void 0&&(oe(i),Y(i))){let c=i._readRequests;i._readRequests=new j,c.forEach(m=>{m._closeSteps()})}}function cf(s,i){s._state="errored",s._storedError=i;let c=s._reader;c!==void 0&&(J(c,i),Y(c)?Fe(c,i):Ul(c,i))}function Wr(s){return new TypeError(`ReadableStream.prototype.${s} can only be used on a ReadableStream`)}function lf(s,i){pe(s,i);let c=s?.highWaterMark;return p(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:y(c)}}let ff=s=>s.byteLength;o(ff,"size");class ro{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=lf(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!hf(this))throw df("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!hf(this))throw df("size");return ff}}Object.defineProperties(ro.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ro.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function df(s){return new TypeError(`ByteLengthQueuingStrategy.prototype.${s} can only be used on a ByteLengthQueuingStrategy`)}function hf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_byteLengthQueuingStrategyHighWaterMark")?!1:s instanceof ro}let pf=()=>1;o(pf,"size");class no{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=lf(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!gf(this))throw mf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!gf(this))throw mf("size");return pf}}Object.defineProperties(no.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(no.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function mf(s){return new TypeError(`CountQueuingStrategy.prototype.${s} can only be used on a CountQueuingStrategy`)}function gf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_countQueuingStrategyHighWaterMark")?!1:s instanceof no}function vy(s,i){pe(s,i);let c=s?.cancel,m=s?.flush,A=s?.readableType,I=s?.start,U=s?.transform,V=s?.writableType;return{cancel:c===void 0?void 0:Fy(c,s,`${i} has member 'cancel' that`),flush:m===void 0?void 0:Ty(m,s,`${i} has member 'flush' that`),readableType:A,start:I===void 0?void 0:Ry(I,s,`${i} has member 'start' that`),transform:U===void 0?void 0:ky(U,s,`${i} has member 'transform' that`),writableType:V}}function Ty(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function Ry(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function ky(s,i,c){return Ee(s,c),(m,A)=>S(s,i,[m,A])}function Fy(s,i,c){return Ee(s,c),m=>S(s,i,[m])}class so{constructor(i={},c={},m={}){i===void 0&&(i=null);let A=Ws(c,"Second parameter"),I=Ws(m,"Third parameter"),U=vy(i,"First parameter");if(U.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(U.writableType!==void 0)throw new RangeError("Invalid writableType specified");let V=Qn(I,0),ae=Gs(I),te=Qn(A,1),ce=Gs(A),ge,Te=f(Ot=>{ge=Ot});Oy(this,Te,te,ce,V,ae),xy(this,U),U.start!==void 0?ge(U.start(this._transformStreamController)):ge(void 0)}get readable(){if(!yf(this))throw Ef("readable");return this._readable}get writable(){if(!yf(this))throw Ef("writable");return this._writable}}Object.defineProperties(so.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(so.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Oy(s,i,c,m,A,I){function U(){return i}function V(Te){return Ny(s,Te)}function ae(Te){return qy(s,Te)}function te(){return jy(s)}s._writable=Ig(U,V,te,ae,c,m);function ce(){return Ly(s)}function ge(Te){return Uy(s,Te)}s._readable=rs(U,ce,ge,A,I),s._backpressure=void 0,s._backpressureChangePromise=void 0,s._backpressureChangePromise_resolve=void 0,oo(s,!0),s._transformStreamController=void 0}function yf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_transformStreamController")?!1:s instanceof so}function _f(s,i){kt(s._readable._readableStreamController,i),Ra(s,i)}function Ra(s,i){ao(s._transformStreamController),Zn(s._writable._writableStreamController,i),ka(s)}function ka(s){s._backpressure&&oo(s,!1)}function oo(s,i){s._backpressureChangePromise!==void 0&&s._backpressureChangePromise_resolve(),s._backpressureChangePromise=f(c=>{s._backpressureChangePromise_resolve=c}),s._backpressure=i}class Dr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!io(this))throw uo("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return va(i)}enqueue(i=void 0){if(!io(this))throw uo("enqueue");Cf(this,i)}error(i=void 0){if(!io(this))throw uo("error");By(this,i)}terminate(){if(!io(this))throw uo("terminate");Iy(this)}}Object.defineProperties(Dr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Dr.prototype.enqueue,"enqueue"),o(Dr.prototype.error,"error"),o(Dr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function io(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledTransformStream")?!1:s instanceof Dr}function Py(s,i,c,m,A){i._controlledTransformStream=s,s._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=m,i._cancelAlgorithm=A,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function xy(s,i){let c=Object.create(Dr.prototype),m,A,I;i.transform!==void 0?m=U=>i.transform(U,c):m=U=>{try{return Cf(c,U),h(void 0)}catch(V){return d(V)}},i.flush!==void 0?A=()=>i.flush(c):A=()=>h(void 0),i.cancel!==void 0?I=U=>i.cancel(U):I=()=>h(void 0),Py(s,c,m,A,I)}function ao(s){s._transformAlgorithm=void 0,s._flushAlgorithm=void 0,s._cancelAlgorithm=void 0}function Cf(s,i){let c=s._controlledTransformStream,m=c._readable._readableStreamController;if(!hn(m))throw new TypeError("Readable side is not in a state that permits enqueue");try{dn(m,i)}catch(I){throw Ra(c,I),c._readable._storedError}cy(m)!==c._backpressure&&oo(c,!0)}function By(s,i){_f(s._controlledTransformStream,i)}function bf(s,i){let c=s._transformAlgorithm(i);return w(c,void 0,m=>{throw _f(s._controlledTransformStream,m),m})}function Iy(s){let i=s._controlledTransformStream,c=i._readable._readableStreamController;Gr(c);let m=new TypeError("TransformStream terminated");Ra(i,m)}function Ny(s,i){let c=s._transformStreamController;if(s._backpressure){let m=s._backpressureChangePromise;return w(m,()=>{let A=s._writable;if(A._state==="erroring")throw A._storedError;return bf(c,i)})}return bf(c,i)}function qy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._readable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return ao(c),E(A,()=>(m._state==="errored"?pn(c,m._storedError):(kt(m._readableStreamController,i),Fa(c)),null),I=>(kt(m._readableStreamController,I),pn(c,I),null)),c._finishPromise}function jy(s){let i=s._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=s._readable;i._finishPromise=f((A,I)=>{i._finishPromise_resolve=A,i._finishPromise_reject=I});let m=i._flushAlgorithm();return ao(i),E(m,()=>(c._state==="errored"?pn(i,c._storedError):(Gr(c._readableStreamController),Fa(i)),null),A=>(kt(c._readableStreamController,A),pn(i,A),null)),i._finishPromise}function Ly(s){return oo(s,!1),s._backpressureChangePromise}function Uy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._writable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return ao(c),E(A,()=>(m._state==="errored"?pn(c,m._storedError):(Zn(m._writableStreamController,i),ka(s),Fa(c)),null),I=>(Zn(m._writableStreamController,I),ka(s),pn(c,I),null)),c._finishPromise}function uo(s){return new TypeError(`TransformStreamDefaultController.prototype.${s} can only be used on a TransformStreamDefaultController`)}function Fa(s){s._finishPromise_resolve!==void 0&&(s._finishPromise_resolve(),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function pn(s,i){s._finishPromise_reject!==void 0&&(g(s._finishPromise),s._finishPromise_reject(i),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function Ef(s){return new TypeError(`TransformStream.prototype.${s} can only be used on a TransformStream`)}r.ByteLengthQueuingStrategy=ro,r.CountQueuingStrategy=no,r.ReadableByteStreamController=nr,r.ReadableStream=Ke,r.ReadableStreamBYOBReader=br,r.ReadableStreamBYOBRequest=jr,r.ReadableStreamDefaultController=or,r.ReadableStreamDefaultReader=M,r.TransformStream=so,r.TransformStreamDefaultController=Dr,r.WritableStream=Er,r.WritableStreamDefaultController=fn,r.WritableStreamDefaultWriter=sr})});var xd=z(()=>{if(!globalThis.ReadableStream)try{let r=X("node:process"),{emitWarning:e}=r;try{r.emitWarning=()=>{},Object.assign(globalThis,X("node:stream/web")),r.emitWarning=e}catch(t){throw r.emitWarning=e,t}}catch{Object.assign(globalThis,Pd())}try{let{Blob:r}=X("buffer");r&&!r.prototype.stream&&(r.prototype.stream=function(t){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let l=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=l.byteLength,a.enqueue(new Uint8Array(l)),n===o.size&&a.close()}})})}catch{}});async function*ru(r,e=!0){for(let t of r)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let n=t.byteOffset,o=t.byteOffset+t.byteLength;for(;n!==o;){let a=Math.min(o-n,Bd),u=t.buffer.slice(n,n+a);n+=u.byteLength,yield new Uint8Array(u)}}else yield t;else{let n=0,o=t;for(;n!==o.size;){let u=await o.slice(n,Math.min(o.size,n+Bd)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var iD,Bd,Id,m_,Bt,us=Me(()=>{iD=zr(xd(),1);Bd=65536;Id=class nu{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let n=new TextEncoder;for(let a of e){let u;ArrayBuffer.isView(a)?u=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?u=new Uint8Array(a.slice(0)):a instanceof nu?u=a:u=n.encode(`${a}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let n of ru(this.#e,!1))t+=e.decode(n,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let n of ru(this.#e,!1))e.set(n,t),t+=n.length;return e.buffer}stream(){let e=ru(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let n=await e.next();n.done?t.close():t.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,n=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),u=t<0?Math.max(o+t,0):Math.min(t,o),l=Math.max(u-a,0),f=this.#e,h=[],d=0;for(let E of f){if(d>=l)break;let P=ArrayBuffer.isView(E)?E.byteLength:E.size;if(a&&P<=a)a-=P,u-=P;else{let v;ArrayBuffer.isView(E)?(v=E.subarray(a,Math.min(P,u)),d+=v.byteLength):(v=E.slice(a,Math.min(P,u)),d+=v.size),u-=P,h.push(v),a=0}}let _=new nu([],{type:String(n).toLowerCase()});return _.#r=l,_.#e=h,_}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Id.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});m_=Id,Bt=m_});var g_,y_,Rr,su=Me(()=>{us();g_=class extends Bt{#e=0;#t="";constructor(e,t,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},y_=g_,Rr=y_});function jd(r,e=Bt){var t=`${Nd()}${Nd()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${t}\r +Content-Disposition: form-data; name="`;return r.forEach((a,u)=>typeof a=="string"?n.push(o+ou(u)+`"\r +\r +${a.replace(/\r(?!\n)|(?{us();su();({toStringTag:cs,iterator:__,hasInstance:C_}=Symbol),Nd=Math.random,b_="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),qd=(r,e,t)=>(r+="",/^(Blob|File)$/.test(e&&e[cs])?[(t=t!==void 0?t+"":e[cs]=="File"?e.name:"blob",r),e.name!==t||e[cs]=="blob"?new Rr([e],t,e):e]:[r,e+""]),ou=(r,e)=>(e?r:r.replace(/\r?\n|\r/g,`\r +`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Yr=(r,e,t)=>{if(e.lengthtypeof e[t]!="function")}append(...e){Yr("append",arguments,2),this.#e.push(qd(...e))}delete(e){Yr("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Yr("get",arguments,1),e+="";for(var t=this.#e,n=t.length,o=0;on[0]===e&&t.push(n[1])),t}has(e){return Yr("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Yr("forEach",arguments,1);for(var[n,o]of this)e.call(t,o,n,this)}set(...e){Yr("set",arguments,2);var t=[],n=!0;e=qd(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!t.push(e)):t.push(o)}),n&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var fr,No=Me(()=>{fr=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,iu=Me(()=>{No();et=class extends fr{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var qo,au,ls,Ld,Ud,Md,jo=Me(()=>{qo=Symbol.toStringTag,au=r=>typeof r=="object"&&typeof r.append=="function"&&typeof r.delete=="function"&&typeof r.get=="function"&&typeof r.getAll=="function"&&typeof r.has=="function"&&typeof r.set=="function"&&typeof r.sort=="function"&&r[qo]==="URLSearchParams",ls=r=>r&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&/^(Blob|File)$/.test(r[qo]),Ld=r=>typeof r=="object"&&(r[qo]==="AbortSignal"||r[qo]==="EventTarget"),Ud=(r,e)=>{let t=new URL(e).hostname,n=new URL(r).hostname;return t===n||t.endsWith(`.${n}`)},Md=(r,e)=>{let t=new URL(e).protocol,n=new URL(r).protocol;return t===n}});var Hd=z((CD,$d)=>{if(!globalThis.DOMException)try{let{MessageChannel:r}=X("worker_threads"),e=new r().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(r){r.constructor.name==="DOMException"&&(globalThis.DOMException=r.constructor)}$d.exports=globalThis.DOMException});import{statSync as Gd,createReadStream as E_,promises as w_}from"node:fs";import{basename as A_}from"node:path";var Wd,uu,zd,Jd,Vd,Kd,Yd,Xd,Lo,cu=Me(()=>{Wd=zr(Hd(),1);su();us();({stat:uu}=w_),zd=(r,e)=>Yd(Gd(r),r,e),Jd=(r,e)=>uu(r).then(t=>Yd(t,r,e)),Vd=(r,e)=>uu(r).then(t=>Xd(t,r,e)),Kd=(r,e)=>Xd(Gd(r),r,e),Yd=(r,e,t="")=>new Bt([new Lo({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],{type:t}),Xd=(r,e,t="")=>new Rr([new Lo({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],A_(e),{type:t,lastModified:r.mtimeMs}),Lo=class r{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new r({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await uu(this.#e);if(e>this.lastModified)throw new Wd.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*E_(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Zd={};Af(Zd,{toFormData:()=>F_});function k_(r){let e=r.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",n=t.slice(t.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),n}async function F_(r,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new lu(t[1]||t[2]),o,a,u,l,f,h,d=[],_=new kr,E=C=>{u+=g.decode(C,{stream:!0})},P=C=>{d.push(C)},v=()=>{let C=new Rr(d,h,{type:f});_.append(l,C)},w=()=>{_.append(l,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=E,n.onPartEnd=w,o="",a="",u="",l="",f="",h=null,d.length=0},n.onHeaderField=function(C){o+=g.decode(C,{stream:!0})},n.onHeaderValue=function(C){a+=g.decode(C,{stream:!0})},n.onHeaderEnd=function(){if(a+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(l=C[2]||C[3]||""),h=k_(a),h&&(n.onPartData=P,n.onPartEnd=v)}else o==="content-type"&&(f=a);a="",o=""};for await(let C of r)n.write(C);return n.end(),_}var Wt,ke,Qd,Fr,Uo,Mo,D_,fs,S_,v_,T_,R_,Xr,lu,eh=Me(()=>{cu();Io();Wt=0,ke={START_BOUNDARY:Wt++,HEADER_FIELD_START:Wt++,HEADER_FIELD:Wt++,HEADER_VALUE_START:Wt++,HEADER_VALUE:Wt++,HEADER_VALUE_ALMOST_DONE:Wt++,HEADERS_ALMOST_DONE:Wt++,PART_DATA_START:Wt++,PART_DATA:Wt++,END:Wt++},Qd=1,Fr={PART_BOUNDARY:Qd,LAST_BOUNDARY:Qd*=2},Uo=10,Mo=13,D_=32,fs=45,S_=58,v_=97,T_=122,R_=r=>r|32,Xr=()=>{},lu=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Xr,this.onHeaderField=Xr,this.onHeadersEnd=Xr,this.onHeaderValue=Xr,this.onPartBegin=Xr,this.onPartData=Xr,this.onPartEnd=Xr,this.boundaryChars={},e=`\r +--`+e;let t=new Uint8Array(e.length);for(let n=0;n{this[N+"Mark"]=t},C=N=>{delete this[N+"Mark"]},R=(N,j,L,H)=>{(j===void 0||j!==L)&&this[N](H&&H.subarray(j,L))},S=(N,j)=>{let L=N+"Mark";L in this&&(j?(R(N,this[L],t,e),delete this[L]):(R(N,this[L],e.length,e),this[L]=0))};for(t=0;tT_)return;break;case ke.HEADER_VALUE_START:if(v===D_)break;g("onHeaderValue"),h=ke.HEADER_VALUE;case ke.HEADER_VALUE:v===Mo&&(S("onHeaderValue",!0),R("onHeaderEnd"),h=ke.HEADER_VALUE_ALMOST_DONE);break;case ke.HEADER_VALUE_ALMOST_DONE:if(v!==Uo)return;h=ke.HEADER_FIELD_START;break;case ke.HEADERS_ALMOST_DONE:if(v!==Uo)return;R("onHeadersEnd"),h=ke.PART_DATA_START;break;case ke.PART_DATA_START:h=ke.PART_DATA,g("onPartData");case ke.PART_DATA:if(o=f,f===0){for(t+=E;t0)a[f-1]=v;else if(o>0){let N=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);R("onPartData",0,o,N),o=0,g("onPartData"),t--}break;case ke.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}S("onHeaderField"),S("onHeaderValue"),S("onPartData"),this.index=f,this.state=h,this.flags=d}end(){if(this.state===ke.HEADER_FIELD_START&&this.index===0||this.state===ke.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==ke.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Or,{PassThrough as th}from"node:stream";import{types as rh,deprecate as du,promisify as O_}from"node:util";import{Buffer as At}from"node:buffer";async function fu(r){if(r[it].disturbed)throw new TypeError(`body used already for: ${r.url}`);if(r[it].disturbed=!0,r[it].error)throw r[it].error;let{body:e}=r;if(e===null)return At.alloc(0);if(!(e instanceof Or))return At.alloc(0);let t=[],n=0;try{for await(let o of e){if(r.size>0&&n+o.length>r.size){let a=new et(`content size at ${r.url} over limit: ${r.size}`,"max-size");throw e.destroy(a),a}n+=o.length,t.push(o)}}catch(o){throw o instanceof fr?o:new et(`Invalid response body while trying to fetch ${r.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?At.from(t.join("")):At.concat(t,n)}catch(o){throw new et(`Could not create Buffer from response body for ${r.url}: ${o.message}`,"system",o)}else throw new et(`Premature close of server response while trying to fetch ${r.url}`)}var P_,it,zt,Sn,x_,$o,nh,sh,Ho=Me(()=>{us();Io();iu();No();jo();P_=O_(Or.pipeline),it=Symbol("Body internals"),zt=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:au(e)?e=At.from(e.toString()):ls(e)||At.isBuffer(e)||(rh.isAnyArrayBuffer(e)?e=At.from(e):ArrayBuffer.isView(e)?e=At.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Or||(e instanceof kr?(e=jd(e),n=e.type.split("=")[1]):e=At.from(String(e))));let o=e;At.isBuffer(e)?o=Or.Readable.from(e):ls(e)&&(o=Or.Readable.from(e.stream())),this[it]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof Or&&e.on("error",a=>{let u=a instanceof fr?a:new et(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await fu(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new kr,o=new URLSearchParams(await this.text());for(let[a,u]of o)n.append(a,u);return n}let{toFormData:t}=await Promise.resolve().then(()=>(eh(),Zd));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",t=await this.arrayBuffer();return new Bt([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await fu(this);return new TextDecoder().decode(e)}buffer(){return fu(this)}};zt.prototype.buffer=du(zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:du(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Sn=(r,e)=>{let t,n,{body:o}=r[it];if(r.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Or&&typeof o.getBoundary!="function"&&(t=new th({highWaterMark:e}),n=new th({highWaterMark:e}),o.pipe(t),o.pipe(n),r[it].stream=t,o=n),o},x_=du(r=>r.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),$o=(r,e)=>r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":au(r)?"application/x-www-form-urlencoded;charset=UTF-8":ls(r)?r.type||null:At.isBuffer(r)||rh.isAnyArrayBuffer(r)||ArrayBuffer.isView(r)?null:r instanceof kr?`multipart/form-data; boundary=${e[it].boundary}`:r&&typeof r.getBoundary=="function"?`multipart/form-data;boundary=${x_(r)}`:r instanceof Or?null:"text/plain;charset=UTF-8",nh=r=>{let{body:e}=r[it];return e===null?0:ls(e)?e.size:At.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},sh=async(r,{body:e})=>{e===null?r.end():await P_(e,r)}});import{types as oh}from"node:util";import Wo from"node:http";function ih(r=[]){return new at(r.reduce((e,t,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return Go(e),hu(e,String(t)),!0}catch{return!1}}))}var Go,hu,at,zo=Me(()=>{Go=typeof Wo.validateHeaderName=="function"?Wo.validateHeaderName:r=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(r)){let e=new TypeError(`Header name must be a valid HTTP token [${r}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},hu=typeof Wo.validateHeaderValue=="function"?Wo.validateHeaderValue:(r,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${r}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},at=class r extends URLSearchParams{constructor(e){let t=[];if(e instanceof r){let n=e.raw();for(let[o,a]of Object.entries(n))t.push(...a.map(u=>[o,u]))}else if(e!=null)if(typeof e=="object"&&!oh.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)t.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||oh.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)");return t=t.length>0?t.map(([n,o])=>(Go(n),hu(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(n,o,a){switch(o){case"append":case"set":return(u,l)=>(Go(u),hu(u,String(l)),URLSearchParams.prototype[o].call(n,String(u).toLowerCase(),String(l)));case"delete":case"has":case"getAll":return u=>(Go(u),URLSearchParams.prototype[o].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t==="host"?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((r,e)=>(r[e]={enumerable:!0},r),{}))});var B_,ds,pu=Me(()=>{B_=new Set([301,302,303,307,308]),ds=r=>B_.has(r)});var It,ft,ah=Me(()=>{zo();Ho();pu();It=Symbol("Response internals"),ft=class r extends zt{constructor(e=null,t={}){super(e,t);let n=t.status!=null?t.status:200,o=new at(t.headers);if(e!==null&&!o.has("Content-Type")){let a=$o(e,this);a&&o.append("Content-Type",a)}this[It]={type:"default",url:t.url,status:n,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[It].type}get url(){return this[It].url||""}get status(){return this[It].status}get ok(){return this[It].status>=200&&this[It].status<300}get redirected(){return this[It].counter>0}get statusText(){return this[It].statusText}get headers(){return this[It].headers}get highWaterMark(){return this[It].highWaterMark}clone(){return new r(Sn(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!ds(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new r(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new r(null,{status:0,statusText:""});return e[It].type="error",e}static json(e=void 0,t={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let o=new at(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new r(n,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(ft.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var uh,ch=Me(()=>{uh=r=>{if(r.search)return r.search;let e=r.href.length-1,t=r.hash||(r.href[e]==="#"?"#":"");return r.href[e-t.length]==="?"?"?":""}});import{isIP as I_}from"node:net";function lh(r,e=!1){return r==null||(r=new URL(r),/^(about|blob|data):$/.test(r.protocol))?"no-referrer":(r.username="",r.password="",r.hash="",e&&(r.pathname="",r.search=""),r)}function hh(r){if(!fh.has(r))throw new TypeError(`Invalid referrerPolicy: ${r}`);return r}function N_(r){if(/^(http|ws)s:$/.test(r.protocol))return!0;let e=r.host.replace(/(^\[)|(]$)/g,""),t=I_(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:r.host==="localhost"||r.host.endsWith(".localhost")?!1:r.protocol==="file:"}function vn(r){return/^about:(blank|srcdoc)$/.test(r)||r.protocol==="data:"||/^(blob|filesystem):$/.test(r.protocol)?!0:N_(r)}function ph(r,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(r.referrer==="no-referrer"||r.referrerPolicy==="")return null;let n=r.referrerPolicy;if(r.referrer==="about:client")return"no-referrer";let o=r.referrer,a=lh(o),u=lh(o,!0);a.toString().length>4096&&(a=u),e&&(a=e(a)),t&&(u=t(u));let l=new URL(r.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return a;case"strict-origin":return vn(a)&&!vn(l)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return a.origin===l.origin?a:vn(a)&&!vn(l)?"no-referrer":u;case"same-origin":return a.origin===l.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===l.origin?a:u;case"no-referrer-when-downgrade":return vn(a)&&!vn(l)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function mh(r){let e=(r.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let n of e)n&&fh.has(n)&&(t=n);return t}var fh,dh,mu=Me(()=>{fh=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),dh="strict-origin-when-cross-origin"});import{format as q_}from"node:url";import{deprecate as j_}from"node:util";var We,hs,L_,Pr,gh,yh=Me(()=>{zo();Ho();jo();ch();mu();We=Symbol("Request internals"),hs=r=>typeof r=="object"&&typeof r[We]=="object",L_=j_(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Pr=class r extends zt{constructor(e,t={}){let n;if(hs(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!hs(t)&&"data"in t&&L_(),(t.body!=null||hs(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:hs(e)&&e.body!==null?Sn(e):null;super(a,{size:t.size||e.size||0});let u=new at(t.headers||e.headers||{});if(a!==null&&!u.has("Content-Type")){let h=$o(a,this);h&&u.set("Content-Type",h)}let l=hs(e)?e.signal:null;if("signal"in t&&(l=t.signal),l!=null&&!Ld(l))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let f=t.referrer==null?e.referrer:t.referrer;if(f==="")f="no-referrer";else if(f){let h=new URL(f);f=/^about:(\/\/)?client$/.test(h)?"client":h}else f=void 0;this[We]={method:o,redirect:t.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:l,referrer:f},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[We].method}get url(){return q_(this[We].parsedURL)}get headers(){return this[We].headers}get redirect(){return this[We].redirect}get signal(){return this[We].signal}get referrer(){if(this[We].referrer==="no-referrer")return"";if(this[We].referrer==="client")return"about:client";if(this[We].referrer)return this[We].referrer.toString()}get referrerPolicy(){return this[We].referrerPolicy}set referrerPolicy(e){this[We].referrerPolicy=hh(e)}clone(){return new r(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Pr.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});gh=r=>{let{parsedURL:e}=r[We],t=new at(r[We].headers);t.has("Accept")||t.set("Accept","*/*");let n=null;if(r.body===null&&/^(post|put)$/i.test(r.method)&&(n="0"),r.body!==null){let l=nh(r);typeof l=="number"&&!Number.isNaN(l)&&(n=String(l))}n&&t.set("Content-Length",n),r.referrerPolicy===""&&(r.referrerPolicy=dh),r.referrer&&r.referrer!=="no-referrer"?r[We].referrer=ph(r):r[We].referrer="no-referrer",r[We].referrer instanceof URL&&t.set("Referer",r.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),r.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=r;typeof o=="function"&&(o=o(e));let a=uh(e),u={path:e.pathname+a,method:r.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:r.insecureHTTPParser,agent:o};return{parsedURL:e,options:u}}});var ps,_h=Me(()=>{No();ps=class extends fr{constructor(e,t="aborted"){super(e,t)}}});var Eh={};Af(Eh,{AbortError:()=>ps,Blob:()=>Bt,FetchError:()=>et,File:()=>Rr,FormData:()=>kr,Headers:()=>at,Request:()=>Pr,Response:()=>ft,blobFrom:()=>Jd,blobFromSync:()=>zd,default:()=>gu,fileFrom:()=>Vd,fileFromSync:()=>Kd,isRedirect:()=>ds});import U_ from"node:http";import M_ from"node:https";import Tn from"node:zlib";import Ch,{PassThrough as bh,pipeline as Rn}from"node:stream";import{Buffer as Jo}from"node:buffer";async function gu(r,e){return new Promise((t,n)=>{let o=new Pr(r,e),{parsedURL:a,options:u}=gh(o);if(!$_.has(a.protocol))throw new TypeError(`node-fetch cannot load ${r}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let v=kd(o.url),w=new ft(v,{headers:{"Content-Type":v.typeFull}});t(w);return}let l=(a.protocol==="https:"?M_:U_).request,{signal:f}=o,h=null,d=()=>{let v=new ps("The operation was aborted.");n(v),o.body&&o.body instanceof Ch.Readable&&o.body.destroy(v),!(!h||!h.body)&&h.body.emit("error",v)};if(f&&f.aborted){d();return}let _=()=>{d(),P()},E=l(a.toString(),u);f&&f.addEventListener("abort",_);let P=()=>{E.abort(),f&&f.removeEventListener("abort",_)};E.on("error",v=>{n(new et(`request to ${o.url} failed, reason: ${v.message}`,"system",v)),P()}),H_(E,v=>{h&&h.body&&h.body.destroy(v)}),process.version<"v14"&&E.on("socket",v=>{let w;v.prependListener("end",()=>{w=v._eventsCount}),v.prependListener("close",g=>{if(h&&w{E.setTimeout(0);let w=ih(v.rawHeaders);if(ds(v.statusCode)){let N=w.get("Location"),j=null;try{j=N===null?null:new URL(N,o.url)}catch{if(o.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${N}`,"invalid-redirect")),P();return}}switch(o.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),P();return;case"manual":break;case"follow":{if(j===null)break;if(o.counter>=o.follow){n(new et(`maximum redirect reached at: ${o.url}`,"max-redirect")),P();return}let L={headers:new at(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Sn(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Ud(o.url,j)||!Md(o.url,j))for(let K of["authorization","www-authenticate","cookie","cookie2"])L.headers.delete(K);if(v.statusCode!==303&&o.body&&e.body instanceof Ch.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),P();return}(v.statusCode===303||(v.statusCode===301||v.statusCode===302)&&o.method==="POST")&&(L.method="GET",L.body=void 0,L.headers.delete("content-length"));let H=mh(w);H&&(L.referrerPolicy=H),t(gu(new Pr(j,L))),P();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}f&&v.once("end",()=>{f.removeEventListener("abort",_)});let g=Rn(v,new bh,N=>{N&&n(N)});process.version<"v12.10"&&v.on("aborted",_);let C={url:o.url,status:v.statusCode,statusText:v.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},R=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||R===null||v.statusCode===204||v.statusCode===304){h=new ft(g,C),t(h);return}let S={flush:Tn.Z_SYNC_FLUSH,finishFlush:Tn.Z_SYNC_FLUSH};if(R==="gzip"||R==="x-gzip"){g=Rn(g,Tn.createGunzip(S),N=>{N&&n(N)}),h=new ft(g,C),t(h);return}if(R==="deflate"||R==="x-deflate"){let N=Rn(v,new bh,j=>{j&&n(j)});N.once("data",j=>{(j[0]&15)===8?g=Rn(g,Tn.createInflate(),L=>{L&&n(L)}):g=Rn(g,Tn.createInflateRaw(),L=>{L&&n(L)}),h=new ft(g,C),t(h)}),N.once("end",()=>{h||(h=new ft(g,C),t(h))});return}if(R==="br"){g=Rn(g,Tn.createBrotliDecompress(),N=>{N&&n(N)}),h=new ft(g,C),t(h);return}h=new ft(g,C),t(h)}),sh(E,o).catch(n)})}function H_(r,e){let t=Jo.from(`0\r +\r +`),n=!1,o=!1,a;r.on("response",u=>{let{headers:l}=u;n=l["transfer-encoding"]==="chunked"&&!l["content-length"]}),r.on("socket",u=>{let l=()=>{if(n&&!o){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},f=h=>{o=Jo.compare(h.slice(-5),t)===0,!o&&a&&(o=Jo.compare(a.slice(-3),t.slice(0,3))===0&&Jo.compare(h.slice(-2),t.slice(3))===0),a=h};u.prependListener("close",l),u.on("data",f),r.on("close",()=>{u.removeListener("close",l),u.removeListener("data",f)})})}var $_,wh=Me(()=>{Fd();Ho();ah();zo();yh();iu();_h();pu();Io();jo();mu();cu();$_=new Set(["data:","http:","https:"])});var Sh=z(Fn=>{"use strict";var G_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},kn;Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Gaxios=void 0;var W_=G_(Ga()),z_=X("https"),Qr=Ja(),J_=sd(),Ah=X("stream"),Dh=Ya(),V_=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Vo=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Dh.GaxiosInterceptorManager,response:new Dh.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&kn.mergeHeaders(a,t.headers),n&&kn.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await kn.#u(),n={...e};delete n.data;let o=await t(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of e.data??[])o.push(a);t.data=o}let n=Qr.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Qr.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;t instanceof Qr.GaxiosError?n=t:t instanceof Error?n=new Qr.GaxiosError(t.message,e,void 0,t):n=new Qr.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await(0,J_.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,t){if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r +Content-Type: ${a}\r +\r +`,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r +`}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>zr(Rd()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(wh(),Eh))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((a,u)=>{u==="set-cookie"?e.append(u,a):e.set(u,a)});return e}};Fn.Gaxios=Vo;kn=Vo});var Je=z(tt=>{"use strict";var K_=tt&&tt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Y_=tt&&tt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&K_(e,r,t)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=Q_;var vh=Sh();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return vh.Gaxios}});var X_=Ja();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return X_.GaxiosError}});Y_(Ya(),tt);tt.instance=new vh.Gaxios;async function Q_(r){return tt.instance.request(r)}});var yu=z((Th,Ko)=>{(function(r){"use strict";var e,t=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,a="[BigNumber Error] ",u=a+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],_=1e7,E=1e9;function P(j){var L,H,K,W=G.prototype={constructor:G,toString:null,valueOf:null},Ae=new G(1),he=20,fe=4,ye=-7,re=21,de=-1e7,Z=1e7,ue=!1,J=1,se=0,oe={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",je=!0;function G(p,y){var b,x,T,F,q,D,k,B,O=this;if(!(O instanceof G))return new G(p,y);if(y==null){if(p&&p._isBigNumber===!0){O.s=p.s,!p.c||p.e>Z?O.c=O.e=null:p.e=10;q/=10,F++);F>Z?O.c=O.e=null:(O.e=F,O.c=[p]);return}B=String(p)}else{if(!t.test(B=String(p)))return K(O,B,D);O.s=B.charCodeAt(0)==45?(B=B.slice(1),-1):1}(F=B.indexOf("."))>-1&&(B=B.replace(".","")),(q=B.search(/e/i))>0?(F<0&&(F=q),F+=+B.slice(q+1),B=B.substring(0,q)):F<0&&(F=B.length)}else{if(C(y,2,Ie.length,"Base"),y==10&&je)return O=new G(p),xe(O,he+O.e+1,fe);if(B=String(p),D=typeof p=="number"){if(p*0!=0)return K(O,B,D,y);if(O.s=1/p<0?(B=B.slice(1),-1):1,G.DEBUG&&B.replace(/^0\.0*|\./,"").length>15)throw Error(u+p)}else O.s=B.charCodeAt(0)===45?(B=B.slice(1),-1):1;for(b=Ie.slice(0,y),F=q=0,k=B.length;qF){F=k;continue}}else if(!T&&(B==B.toUpperCase()&&(B=B.toLowerCase())||B==B.toLowerCase()&&(B=B.toUpperCase()))){T=!0,q=-1,F=0;continue}return K(O,String(p),D,y)}D=!1,B=H(B,y,10,O.s),(F=B.indexOf("."))>-1?B=B.replace(".",""):F=B.length}for(q=0;B.charCodeAt(q)===48;q++);for(k=B.length;B.charCodeAt(--k)===48;);if(B=B.slice(q,++k)){if(k-=q,D&&G.DEBUG&&k>15&&(p>h||p!==o(p)))throw Error(u+O.s*p);if((F=F-q-1)>Z)O.c=O.e=null;else if(F=-E&&T<=E&&T===o(T)){if(x[0]===0){if(T===0&&x.length===1)return!0;break e}if(y=(T+1)%f,y<1&&(y+=f),String(x[0]).length==y){for(y=0;y=l||b!==o(b))break e;if(b!==0)return!0}}}else if(x===null&&T===null&&(F===null||F===1||F===-1))return!0;throw Error(a+"Invalid BigNumber: "+p)},G.maximum=G.max=function(){return Ee(arguments,-1)},G.minimum=G.min=function(){return Ee(arguments,1)},G.random=function(){var p=9007199254740992,y=Math.random()*p&2097151?function(){return o(Math.random()*p)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(b){var x,T,F,q,D,k=0,B=[],O=new G(Ae);if(b==null?b=he:C(b,0,E),q=n(b/f),ue)if(crypto.getRandomValues){for(x=crypto.getRandomValues(new Uint32Array(q*=2));k>>11),D>=9e15?(T=crypto.getRandomValues(new Uint32Array(2)),x[k]=T[0],x[k+1]=T[1]):(B.push(D%1e14),k+=2);k=q/2}else if(crypto.randomBytes){for(x=crypto.randomBytes(q*=7);k=9e15?crypto.randomBytes(7).copy(x,k):(B.push(D%1e14),k+=7);k=q/7}else throw ue=!1,Error(a+"crypto unavailable");if(!ue)for(;k=10;D/=10,k++);kT-1&&(D[q+1]==null&&(D[q+1]=0),D[q+1]+=D[q]/T|0,D[q]%=T)}return D.reverse()}return function(b,x,T,F,q){var D,k,B,O,M,Y,Q,we,Fe=b.indexOf("."),Be=he,be=fe;for(Fe>=0&&(O=se,se=0,b=b.replace(".",""),we=new G(x),Y=we.pow(b.length-Fe),se=O,we.c=y(N(w(Y.c),Y.e,"0"),10,T,p),we.e=we.c.length),Q=y(b,x,T,q?(D=Ie,p):(D=p,Ie)),B=O=Q.length;Q[--O]==0;Q.pop());if(!Q[0])return D.charAt(0);if(Fe<0?--B:(Y.c=Q,Y.e=B,Y.s=F,Y=L(Y,we,Be,be,T),Q=Y.c,M=Y.r,B=Y.e),k=B+Be+1,Fe=Q[k],O=T/2,M=M||k<0||Q[k+1]!=null,M=be<4?(Fe!=null||M)&&(be==0||be==(Y.s<0?3:2)):Fe>O||Fe==O&&(be==4||M||be==6&&Q[k-1]&1||be==(Y.s<0?8:7)),k<1||!Q[0])b=M?N(D.charAt(1),-Be,D.charAt(0)):D.charAt(0);else{if(Q.length=k,M)for(--T;++Q[--k]>T;)Q[k]=0,k||(++B,Q=[1].concat(Q));for(O=Q.length;!Q[--O];);for(Fe=0,b="";Fe<=O;b+=D.charAt(Q[Fe++]));b=N(b,B,D.charAt(0))}return b}}(),L=function(){function p(x,T,F){var q,D,k,B,O=0,M=x.length,Y=T%_,Q=T/_|0;for(x=x.slice();M--;)k=x[M]%_,B=x[M]/_|0,q=Q*k+B*Y,D=Y*k+q%_*_+O,O=(D/F|0)+(q/_|0)+Q*B,x[M]=D%F;return O&&(x=[O].concat(x)),x}function y(x,T,F,q){var D,k;if(F!=q)k=F>q?1:-1;else for(D=k=0;DT[D]?1:-1;break}return k}function b(x,T,F,q){for(var D=0;F--;)x[F]-=D,D=x[F]1;x.splice(0,1));}return function(x,T,F,q,D){var k,B,O,M,Y,Q,we,Fe,Be,be,De,Le,sn,on,an,ut,tr,Ve=x.s==T.s?1:-1,Ue=x.c,Se=T.c;if(!Ue||!Ue[0]||!Se||!Se[0])return new G(!x.s||!T.s||(Ue?Se&&Ue[0]==Se[0]:!Se)?NaN:Ue&&Ue[0]==0||!Se?Ve*0:Ve/0);for(Fe=new G(Ve),Be=Fe.c=[],B=x.e-T.e,Ve=F+B+1,D||(D=l,B=v(x.e/f)-v(T.e/f),Ve=Ve/f|0),O=0;Se[O]==(Ue[O]||0);O++);if(Se[O]>(Ue[O]||0)&&B--,Ve<0)Be.push(1),M=!0;else{for(on=Ue.length,ut=Se.length,O=0,Ve+=2,Y=o(D/(Se[0]+1)),Y>1&&(Se=p(Se,Y,D),Ue=p(Ue,Y,D),ut=Se.length,on=Ue.length),sn=ut,be=Ue.slice(0,ut),De=be.length;De=D/2&&an++;do{if(Y=0,k=y(Se,be,ut,De),k<0){if(Le=be[0],ut!=De&&(Le=Le*D+(be[1]||0)),Y=o(Le/an),Y>1)for(Y>=D&&(Y=D-1),Q=p(Se,Y,D),we=Q.length,De=be.length;y(Q,be,we,De)==1;)Y--,b(Q,ut=10;Ve/=10,O++);xe(Fe,F+(Fe.e=O+B*f-1)+1,q,M)}else Fe.e=B,Fe.r=+M;return Fe}}();function pe(p,y,b,x){var T,F,q,D,k;if(b==null?b=fe:C(b,0,8),!p.c)return p.toString();if(T=p.c[0],q=p.e,y==null)k=w(p.c),k=x==1||x==2&&(q<=ye||q>=re)?S(k,q):N(k,q,"0");else if(p=xe(new G(p),y,b),F=p.e,k=w(p.c),D=k.length,x==1||x==2&&(y<=F||F<=ye)){for(;Dq),k=N(k,F,"0"),F+1>D){if(--y>0)for(k+=".";y--;k+="0");}else if(y+=F-D,y>0)for(F+1==D&&(k+=".");y--;k+="0");return p.s<0&&T?"-"+k:k}function Ee(p,y){for(var b,x,T=1,F=new G(p[0]);T=10;T/=10,x++);return(b=x+b*f-1)>Z?p.c=p.e=null:b=10;D/=10,T++);if(F=y-T,F<0)F+=f,q=y,k=M[B=0],O=o(k/Y[T-q-1]%10);else if(B=n((F+1)/f),B>=M.length)if(x){for(;M.length<=B;M.push(0));k=O=0,T=1,F%=f,q=F-f+1}else break e;else{for(k=D=M[B],T=1;D>=10;D/=10,T++);F%=f,q=F-f+T,O=q<0?0:o(k/Y[T-q-1]%10)}if(x=x||y<0||M[B+1]!=null||(q<0?k:k%Y[T-q-1]),x=b<4?(O||x)&&(b==0||b==(p.s<0?3:2)):O>5||O==5&&(b==4||x||b==6&&(F>0?q>0?k/Y[T-q]:0:M[B-1])%10&1||b==(p.s<0?8:7)),y<1||!M[0])return M.length=0,x?(y-=p.e+1,M[0]=Y[(f-y%f)%f],p.e=-y||0):M[0]=p.e=0,p;if(F==0?(M.length=B,D=1,B--):(M.length=B+1,D=Y[f-F],M[B]=q>0?o(k/Y[T-q]%Y[q])*D:0),x)for(;;)if(B==0){for(F=1,q=M[0];q>=10;q/=10,F++);for(q=M[0]+=D,D=1;q>=10;q/=10,D++);F!=D&&(p.e++,M[0]==l&&(M[0]=1));break}else{if(M[B]+=D,M[B]!=l)break;M[B--]=0,D=1}for(F=M.length;M[--F]===0;M.pop());}p.e>Z?p.c=p.e=null:p.e=re?S(y,b):N(y,b,"0"),p.s<0?"-"+y:y)}return W.absoluteValue=W.abs=function(){var p=new G(this);return p.s<0&&(p.s=1),p},W.comparedTo=function(p,y){return g(this,new G(p,y))},W.decimalPlaces=W.dp=function(p,y){var b,x,T,F=this;if(p!=null)return C(p,0,E),y==null?y=fe:C(y,0,8),xe(new G(F),p+F.e+1,y);if(!(b=F.c))return null;if(x=((T=b.length-1)-v(this.e/f))*f,T=b[T])for(;T%10==0;T/=10,x--);return x<0&&(x=0),x},W.dividedBy=W.div=function(p,y){return L(this,new G(p,y),he,fe)},W.dividedToIntegerBy=W.idiv=function(p,y){return L(this,new G(p,y),0,1)},W.exponentiatedBy=W.pow=function(p,y){var b,x,T,F,q,D,k,B,O,M=this;if(p=new G(p),p.c&&!p.isInteger())throw Error(a+"Exponent not an integer: "+Ne(p));if(y!=null&&(y=new G(y)),D=p.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!p.c||!p.c[0])return O=new G(Math.pow(+Ne(M),D?p.s*(2-R(p)):+Ne(p))),y?O.mod(y):O;if(k=p.s<0,y){if(y.c?!y.c[0]:!y.s)return new G(NaN);x=!k&&M.isInteger()&&y.isInteger(),x&&(M=M.mod(y))}else{if(p.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||D&&M.c[1]>=24e7:M.c[0]<8e13||D&&M.c[0]<=9999975e7)))return F=M.s<0&&R(p)?-0:0,M.e>-1&&(F=1/F),new G(k?1/F:F);se&&(F=n(se/f+2))}for(D?(b=new G(.5),k&&(p.s=1),B=R(p)):(T=Math.abs(+Ne(p)),B=T%2),O=new G(Ae);;){if(B){if(O=O.times(M),!O.c)break;F?O.c.length>F&&(O.c.length=F):x&&(O=O.mod(y))}if(T){if(T=o(T/2),T===0)break;B=T%2}else if(p=p.times(b),xe(p,p.e+1,1),p.e>14)B=R(p);else{if(T=+Ne(p),T===0)break;B=T%2}M=M.times(M),F?M.c&&M.c.length>F&&(M.c.length=F):x&&(M=M.mod(y))}return x?O:(k&&(O=Ae.div(O)),y?O.mod(y):F?xe(O,se,fe,q):O)},W.integerValue=function(p){var y=new G(this);return p==null?p=fe:C(p,0,8),xe(y,y.e+1,p)},W.isEqualTo=W.eq=function(p,y){return g(this,new G(p,y))===0},W.isFinite=function(){return!!this.c},W.isGreaterThan=W.gt=function(p,y){return g(this,new G(p,y))>0},W.isGreaterThanOrEqualTo=W.gte=function(p,y){return(y=g(this,new G(p,y)))===1||y===0},W.isInteger=function(){return!!this.c&&v(this.e/f)>this.c.length-2},W.isLessThan=W.lt=function(p,y){return g(this,new G(p,y))<0},W.isLessThanOrEqualTo=W.lte=function(p,y){return(y=g(this,new G(p,y)))===-1||y===0},W.isNaN=function(){return!this.s},W.isNegative=function(){return this.s<0},W.isPositive=function(){return this.s>0},W.isZero=function(){return!!this.c&&this.c[0]==0},W.minus=function(p,y){var b,x,T,F,q=this,D=q.s;if(p=new G(p,y),y=p.s,!D||!y)return new G(NaN);if(D!=y)return p.s=-y,q.plus(p);var k=q.e/f,B=p.e/f,O=q.c,M=p.c;if(!k||!B){if(!O||!M)return O?(p.s=-y,p):new G(M?q:NaN);if(!O[0]||!M[0])return M[0]?(p.s=-y,p):new G(O[0]?q:fe==3?-0:0)}if(k=v(k),B=v(B),O=O.slice(),D=k-B){for((F=D<0)?(D=-D,T=O):(B=k,T=M),T.reverse(),y=D;y--;T.push(0));T.reverse()}else for(x=(F=(D=O.length)<(y=M.length))?D:y,D=y=0;y0)for(;y--;O[b++]=0);for(y=l-1;x>D;){if(O[--x]=0;){for(b=0,Y=Le[T]%Be,Q=Le[T]/Be|0,q=k,F=T+q;F>T;)B=De[--q]%Be,O=De[q]/Be|0,D=Q*B+O*Y,B=Y*B+D%Be*Be+we[F]+b,b=(B/Fe|0)+(D/Be|0)+Q*O,we[F--]=B%Fe;we[F]=b}return b?++x:we.splice(0,1),er(p,we,x)},W.negated=function(){var p=new G(this);return p.s=-p.s||null,p},W.plus=function(p,y){var b,x=this,T=x.s;if(p=new G(p,y),y=p.s,!T||!y)return new G(NaN);if(T!=y)return p.s=-y,x.minus(p);var F=x.e/f,q=p.e/f,D=x.c,k=p.c;if(!F||!q){if(!D||!k)return new G(T/0);if(!D[0]||!k[0])return k[0]?p:new G(D[0]?x:T*0)}if(F=v(F),q=v(q),D=D.slice(),T=F-q){for(T>0?(q=F,b=k):(T=-T,b=D),b.reverse();T--;b.push(0));b.reverse()}for(T=D.length,y=k.length,T-y<0&&(b=k,k=D,D=b,y=T),T=0;y;)T=(D[--y]=D[y]+k[y]+T)/l|0,D[y]=l===D[y]?0:D[y]%l;return T&&(D=[T].concat(D),++q),er(p,D,q)},W.precision=W.sd=function(p,y){var b,x,T,F=this;if(p!=null&&p!==!!p)return C(p,1,E),y==null?y=fe:C(y,0,8),xe(new G(F),p,y);if(!(b=F.c))return null;if(T=b.length-1,x=T*f+1,T=b[T]){for(;T%10==0;T/=10,x--);for(T=b[0];T>=10;T/=10,x++);}return p&&F.e+1>x&&(x=F.e+1),x},W.shiftedBy=function(p){return C(p,-h,h),this.times("1e"+p)},W.squareRoot=W.sqrt=function(){var p,y,b,x,T,F=this,q=F.c,D=F.s,k=F.e,B=he+4,O=new G("0.5");if(D!==1||!q||!q[0])return new G(!D||D<0&&(!q||q[0])?NaN:q?F:1/0);if(D=Math.sqrt(+Ne(F)),D==0||D==1/0?(y=w(q),(y.length+k)%2==0&&(y+="0"),D=Math.sqrt(+y),k=v((k+1)/2)-(k<0||k%2),D==1/0?y="5e"+k:(y=D.toExponential(),y=y.slice(0,y.indexOf("e")+1)+k),b=new G(y)):b=new G(D+""),b.c[0]){for(k=b.e,D=k+B,D<3&&(D=0);;)if(T=b,b=O.times(T.plus(L(F,T,B,1))),w(T.c).slice(0,D)===(y=w(b.c)).slice(0,D))if(b.e0&&we>0){for(F=we%D||D,O=Q.substr(0,F);F0&&(O+=B+Q.slice(F)),Y&&(O="-"+O)}x=M?O+(b.decimalSeparator||"")+((k=+b.fractionGroupSize)?M.replace(new RegExp("\\d{"+k+"}\\B","g"),"$&"+(b.fractionGroupSeparator||"")):M):O}return(b.prefix||"")+x+(b.suffix||"")},W.toFraction=function(p){var y,b,x,T,F,q,D,k,B,O,M,Y,Q=this,we=Q.c;if(p!=null&&(D=new G(p),!D.isInteger()&&(D.c||D.s!==1)||D.lt(Ae)))throw Error(a+"Argument "+(D.isInteger()?"out of range: ":"not an integer: ")+Ne(D));if(!we)return new G(Q);for(y=new G(Ae),B=b=new G(Ae),x=k=new G(Ae),Y=w(we),F=y.e=Y.length-Q.e-1,y.c[0]=d[(q=F%f)<0?f+q:q],p=!p||D.comparedTo(y)>0?F>0?y:B:D,q=Z,Z=1/0,D=new G(Y),k.c[0]=0;O=L(D,y,0,1),T=b.plus(O.times(x)),T.comparedTo(p)!=1;)b=x,x=T,B=k.plus(O.times(T=B)),k=T,y=D.minus(O.times(T=y)),D=T;return T=L(p.minus(b),x,0,1),k=k.plus(T.times(B)),b=b.plus(T.times(x)),k.s=B.s=Q.s,F=F*2,M=L(B,x,F,fe).minus(Q).abs().comparedTo(L(k,b,F,fe).minus(Q).abs())<1?[B,x]:[k,b],Z=q,M},W.toNumber=function(){return+Ne(this)},W.toPrecision=function(p,y){return p!=null&&C(p,1,E),pe(this,p,y,2)},W.toString=function(p){var y,b=this,x=b.s,T=b.e;return T===null?x?(y="Infinity",x<0&&(y="-"+y)):y="NaN":(p==null?y=T<=ye||T>=re?S(w(b.c),T):N(w(b.c),T,"0"):p===10&&je?(b=xe(new G(b),he+T+1,fe),y=N(w(b.c),b.e,"0")):(C(p,2,Ie.length,"Base"),y=H(N(w(b.c),T,"0"),10,p,x,!0)),x<0&&b.c[0]&&(y="-"+y)),y},W.valueOf=W.toJSON=function(){return Ne(this)},W._isBigNumber=!0,j!=null&&G.set(j),G}function v(j){var L=j|0;return j>0||j===L?L:L-1}function w(j){for(var L,H,K=1,W=j.length,Ae=j[0]+"";Kre^H?1:-1;for(fe=(ye=W.length)<(re=Ae.length)?ye:re,he=0;heAe[he]^H?1:-1;return ye==re?0:ye>re^H?1:-1}function C(j,L,H,K){if(jH||j!==o(j))throw Error(a+(K||"Argument")+(typeof j=="number"?jH?" out of range: ":" not an integer: ":" not a primitive number: ")+String(j))}function R(j){var L=j.c.length-1;return v(j.e/f)==L&&j.c[L]%2!=0}function S(j,L){return(j.length>1?j.charAt(0)+"."+j.slice(1):j)+(L<0?"e":"e+")+L}function N(j,L,H){var K,W;if(L<0){for(W=H+".";++L;W+=H);j=W+j}else if(K=j.length,++L>K){for(W=H,L-=K;--L;W+=H);j+=W}else L{var Rh=yu(),kh=Fh.exports;(function(){"use strict";function r(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,a={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function l(h){return t.lastIndex=0,t.test(h)?'"'+h.replace(t,function(d){var _=a[d];return typeof _=="string"?_:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function f(h,d){var _,E,P,v,w=n,g,C=d[h],R=C!=null&&(C instanceof Rh||Rh.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(h)),typeof u=="function"&&(C=u.call(d,h,C)),typeof C){case"string":return R?C:l(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(n+=o,g=[],Object.prototype.toString.apply(C)==="[object Array]"){for(v=C.length,_=0;_{var Yo=null,Z_=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,eC=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,tC=function(r){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(r!=null){if(r.strict===!0&&(e.strict=!0),r.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=r.alwaysParseAsBig===!0?r.alwaysParseAsBig:!1,e.useNativeBigInt=r.useNativeBigInt===!0?r.useNativeBigInt:!1,typeof r.constructorAction<"u")if(r.constructorAction==="error"||r.constructorAction==="ignore"||r.constructorAction==="preserve")e.constructorAction=r.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${r.constructorAction}`);if(typeof r.protoAction<"u")if(r.protoAction==="error"||r.protoAction==="ignore"||r.protoAction==="preserve")e.protoAction=r.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${r.protoAction}`)}var t,n,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},a,u=function(w){throw{name:"SyntaxError",message:w,at:t,text:a}},l=function(w){return w&&w!==n&&u("Expected '"+w+"' instead of '"+n+"'"),n=a.charAt(t),t+=1,n},f=function(){var w,g="";for(n==="-"&&(g="-",l("-"));n>="0"&&n<="9";)g+=n,l();if(n===".")for(g+=".";l()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,l(),(n==="-"||n==="+")&&(g+=n,l());n>="0"&&n<="9";)g+=n,l();if(w=+g,!isFinite(w))u("Bad number");else return Yo==null&&(Yo=yu()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Yo(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(w):new Yo(w):w},h=function(){var w,g,C="",R;if(n==='"')for(var S=t;l();){if(n==='"')return t-1>S&&(C+=a.substring(S,t-1)),l(),C;if(n==="\\"){if(t-1>S&&(C+=a.substring(S,t-1)),l(),n==="u"){for(R=0,g=0;g<4&&(w=parseInt(l(),16),!!isFinite(w));g+=1)R=R*16+w;C+=String.fromCharCode(R)}else if(typeof o[n]=="string")C+=o[n];else break;S=t}}u("Bad string")},d=function(){for(;n&&n<=" ";)l()},_=function(){switch(n){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}u("Unexpected '"+n+"'")},E,P=function(){var w=[];if(n==="["){if(l("["),d(),n==="]")return l("]"),w;for(;n;){if(w.push(E()),d(),n==="]")return l("]"),w;l(","),d()}}u("Bad array")},v=function(){var w,g=Object.create(null);if(n==="{"){if(l("{"),d(),n==="}")return l("}"),g;for(;n;){if(w=h(),d(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(g,w)&&u('Duplicate key "'+w+'"'),Z_.test(w)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?E():g[w]=E():eC.test(w)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?E():g[w]=E():g[w]=E(),d(),n==="}")return l("}"),g;l(","),d()}}u("Bad object")};return E=function(){switch(d(),n){case"{":return v();case"[":return P();case'"':return h();case"-":return f();default:return n>="0"&&n<="9"?f():_()}},function(w,g){var C;return a=w+"",t=0,n=" ",C=E(),d(),n&&u("Syntax error"),typeof g=="function"?function R(S,N){var j,L,H=S[N];return H&&typeof H=="object"&&Object.keys(H).forEach(function(K){L=R(H,K),L!==void 0?H[K]=L:delete H[K]}),g.call(S,N,H)}({"":C},""):C}};Ph.exports=tC});var Nh=z((DS,Xo)=>{var Bh=Oh().stringify,Ih=xh();Xo.exports=function(r){return{parse:Ih(r),stringify:Bh}};Xo.exports.parse=Ih();Xo.exports.stringify=Bh});var _u=z(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.GCE_LINUX_BIOS_PATHS=void 0;Nt.isGoogleCloudServerless=Lh;Nt.isGoogleComputeEngineLinux=Uh;Nt.isGoogleComputeEngineMACAddress=Mh;Nt.isGoogleComputeEngine=$h;Nt.detectGCPResidency=nC;var qh=X("fs"),jh=X("os");Nt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var rC=/^42:01/;function Lh(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Uh(){if((0,jh.platform)()!=="linux")return!1;try{(0,qh.statSync)(Nt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let r=(0,qh.readFileSync)(Nt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(r)}catch{return!1}}function Mh(){let r=(0,jh.networkInterfaces)();for(let e of Object.values(r))if(e){for(let{mac:t}of e)if(rC.test(t))return!0}return!1}function $h(){return Uh()||Mh()}function nC(){return Lh()||$h()}});var Hh=z(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.Colours=void 0;var Xe=class r{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){r.enabled=r.isEnabled(process==null?void 0:process.stderr),this.enabled?(r.reset="\x1B[0m",r.bright="\x1B[1m",r.dim="\x1B[2m",r.red="\x1B[31m",r.green="\x1B[32m",r.yellow="\x1B[33m",r.blue="\x1B[34m",r.magenta="\x1B[35m",r.cyan="\x1B[36m",r.white="\x1B[37m",r.grey="\x1B[90m"):(r.reset="",r.bright="",r.dim="",r.red="",r.green="",r.yellow="",r.blue="",r.magenta="",r.cyan="",r.white="",r.grey="")}};Qo.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var Jh=z(ve=>{"use strict";var sC=ve&&ve.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),oC=ve&&ve.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),Gh=ve&&ve.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;othis.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>zh(n,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch{}try{this.emit("log",e,t)}catch{}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};ve.AdhocDebugLogger=gs;ve.placeholder=new gs("",()=>{}).func;var On=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=ms.env[ve.env.nodeEnables])!==null&&e!==void 0?e:"*";t==="all"&&(t="*"),this.filters=t.split(",")}log(e,t,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(t,...n)}catch(o){console.error(o)}}};ve.DebugLogBackendBase=On;var Cu=class extends On{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...n)=>{var o;let a=`${dt.Colours.green}${e}${dt.Colours.reset}`,u=`${dt.Colours.yellow}${ms.pid}${dt.Colours.reset}`,l;switch(t.severity){case qt.ERROR:l=`${dt.Colours.red}${t.severity}${dt.Colours.reset}`;break;case qt.INFO:l=`${dt.Colours.magenta}${t.severity}${dt.Colours.reset}`;break;case qt.WARNING:l=`${dt.Colours.yellow}${t.severity}${dt.Colours.reset}`;break;default:l=(o=t.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let f=Wh.formatWithOptions({colors:dt.Colours.enabled},...n),h=Object.assign({},t);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",_=d?`${dt.Colours.grey}${d}${dt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,a,l,f,d?` ${_}`:"")}:()=>{}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}};function bu(){return new Cu}var Eu=class extends On{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(n,...o)=>{t(o[0],...o.slice(1))}}setFilters(){var e;let t=(e=ms.env.NODE_DEBUG)!==null&&e!==void 0?e:"";ms.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}};function aC(r){return new Eu(r)}var wu=class extends On{constructor(e){var t;super(),this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let n=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(o,...a)=>{var u;let l=(u=o.severity)!==null&&u!==void 0?u:qt.INFO,f=Object.assign({severity:l,message:Wh.format(...a)},o),h=JSON.stringify(f);n?n(o,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function uC(r){return new wu(r)}ve.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Au=new Map,ht;function cC(r){ht=r,Au.clear()}function zh(r,e){if(!ht&&!ms.env[ve.env.nodeEnables]||!r)return ve.placeholder;e&&(r=`${e.instance.namespace}:${r}`);let t=Au.get(r);if(t)return t.func;if(ht===null)return ve.placeholder;ht===void 0&&(ht=bu());let n=(()=>{let o;return new gs(r,(u,...l)=>{if(o!==ht){if(ht===null)return;ht===void 0&&(ht=bu()),o=ht}ht?.log(r,u,...l)})})();return Au.set(r,n),n.func}});var Du=z(Zr=>{"use strict";var lC=Zr&&Zr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),fC=Zr&&Zr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&lC(e,r,t)};Object.defineProperty(Zr,"__esModule",{value:!0});fC(Jh(),Zr)});var _s=z(ie=>{"use strict";var Kh=ie&&ie.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),dC=ie&&ie.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),hC=ie&&ie.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;o{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ys(r,e={},t=3,n=!1){let o=new Headers(ie.HEADERS),a="",u={};if(typeof r=="object"){let _=r;new Headers(_.headers).forEach((E,P)=>o.set(P,E)),a=_.metadataKey,u=_.params||u,t=_.noResponseRetries||t,n=_.fastFail||n}else a=r;typeof e=="string"?a+=`/${e}`:(_C(e),e.property&&(a+=`/${e.property}`),new Headers(e.headers).forEach((_,E)=>o.set(E,_)),u=e.params||u);let l=n?CC:Su.request,f={url:`${vu()}/${a}`,headers:o,retryConfig:{noResponseRetries:t},params:u,responseType:"text",timeout:Xh()};Vh.info("instance request %j",f);let h=await l(f);Vh.info("instance metadata is %s",h.data);let d=h.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return mC.parse(h.data)}catch{}return h.data}async function CC(r){let e={...r,url:r.url?.toString().replace(vu(),vu(ie.SECONDARY_HOST_ADDRESS))},t=(0,Su.request)(r),n=(0,Su.request)(e);return Promise.any([t,n])}function bC(r){return ys("instance",r)}function EC(r){return ys("project",r)}function wC(r){return ys("universe",r)}async function AC(r){let e={};return await Promise.all(r.map(t=>(async()=>{let n=await ys(t),o=t.metadataKey;e[o]=n})())),e}function DC(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Zo;async function SC(){if(process.env.METADATA_SERVER_DETECTION){let r=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(r in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${r}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(r){case"assume-present":return!0;case"none":return!1;case"bios-only":return Tu();case"ping-only":}}try{return Zo===void 0&&(Zo=ys("instance",void 0,DC(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Zo,!0}catch(r){let e=r;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let t="UNKNOWN";e.code&&(t=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${t}`,"MetadataLookupWarning")}return!1}}function vC(){Zo=void 0}ie.gcpResidencyCache=null;function Tu(){return ie.gcpResidencyCache===null&&Yh(),ie.gcpResidencyCache}function Yh(r=null){ie.gcpResidencyCache=r!==null?r:(0,gC.detectGCPResidency)()}function Xh(){return Tu()?0:3e3}pC(_u(),ie)});var ep=z(ei=>{"use strict";ei.byteLength=RC;ei.toByteArray=FC;ei.fromByteArray=xC;var Jt=[],Dt=[],TC=typeof Uint8Array<"u"?Uint8Array:Array,Ru="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(en=0,Qh=Ru.length;en0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function RC(r){var e=Zh(r),t=e[0],n=e[1];return(t+n)*3/4-n}function kC(r,e,t){return(e+t)*3/4-t}function FC(r){var e,t=Zh(r),n=t[0],o=t[1],a=new TC(kC(r,n,o)),u=0,l=o>0?n-4:n,f;for(f=0;f>16&255,a[u++]=e>>8&255,a[u++]=e&255;return o===2&&(e=Dt[r.charCodeAt(f)]<<2|Dt[r.charCodeAt(f+1)]>>4,a[u++]=e&255),o===1&&(e=Dt[r.charCodeAt(f)]<<10|Dt[r.charCodeAt(f+1)]<<4|Dt[r.charCodeAt(f+2)]>>2,a[u++]=e>>8&255,a[u++]=e&255),a}function OC(r){return Jt[r>>18&63]+Jt[r>>12&63]+Jt[r>>6&63]+Jt[r&63]}function PC(r,e,t){for(var n,o=[],a=e;al?l:u+a));return n===1?(e=r[t-1],o.push(Jt[e>>2]+Jt[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],o.push(Jt[e>>10]+Jt[e>>4&63]+Jt[e<<2&63]+"=")),o.join("")}});var Fu=z(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.fromArrayBufferToHex=BC;function BC(r){return Array.from(new Uint8Array(r)).map(t=>t.toString(16).padStart(2,"0")).join("")}});var tp=z(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.BrowserCrypto=void 0;var Pn=ep(),IC=Fu(),Ou=class r{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return Pn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),Pn.fromByteArray(t)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,t,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},a=new TextEncoder().encode(t),u=Pn.toByteArray(r.padBase64(n)),l=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,l,u,a)}async sign(e,t){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(t),a=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,a,o);return Pn.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let t=Pn.toByteArray(r.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return Pn.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return(0,IC.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,a=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",a,o.encode(t))}};ti.BrowserCrypto=Ou});var rp=z(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.NodeCrypto=void 0;var xn=X("crypto"),Pu=class{async sha256DigestBase64(e){return xn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return xn.randomBytes(e).toString("base64")}async verify(e,t,n){let o=xn.createVerify("RSA-SHA256");return o.update(t),o.end(),o.verify(e,n,"base64")}async sign(e,t){let n=xn.createSign("RSA-SHA256");return n.update(t),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return xn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:qC(e);return NC(xn.createHmac("sha256",n).update(t).digest())}};ri.NodeCrypto=Pu;function NC(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function qC(r){return Buffer.from(r)}});var Cs=z(dr=>{"use strict";var jC=dr&&dr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),LC=dr&&dr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&jC(e,r,t)};Object.defineProperty(dr,"__esModule",{value:!0});dr.createCrypto=$C;dr.hasBrowserCrypto=np;var UC=tp(),MC=rp();LC(Fu(),dr);function $C(){return np()?new UC.BrowserCrypto:new MC.NodeCrypto}function np(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Bn=z((xu,op)=>{var ni=X("buffer"),Vt=ni.Buffer;function sp(r,e){for(var t in r)e[t]=r[t]}Vt.from&&Vt.alloc&&Vt.allocUnsafe&&Vt.allocUnsafeSlow?op.exports=ni:(sp(ni,xu),xu.Buffer=tn);function tn(r,e,t){return Vt(r,e,t)}tn.prototype=Object.create(Vt.prototype);sp(Vt,tn);tn.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return Vt(r,e,t)};tn.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=Vt(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};tn.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Vt(r)};tn.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ni.SlowBuffer(r)}});var ap=z((IS,ip)=>{"use strict";function Bu(r){var e=(r/8|0)+(r%8===0?0:1);return e}var HC={ES256:Bu(256),ES384:Bu(384),ES512:Bu(521)};function GC(r){var e=HC[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}ip.exports=GC});var Iu=z((NS,hp)=>{"use strict";var si=Bn().Buffer,cp=ap(),oi=128,lp=0,WC=32,zC=16,JC=2,fp=zC|WC|lp<<6,ii=JC|lp<<6;function VC(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function dp(r){if(si.isBuffer(r))return r;if(typeof r=="string")return si.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function KC(r,e){r=dp(r);var t=cp(e),n=t+1,o=r.length,a=0;if(r[a++]!==fp)throw new Error('Could not find expected "seq"');var u=r[a++];if(u===(oi|1)&&(u=r[a++]),o-a=oi;return o&&--n,n}function YC(r,e){r=dp(r);var t=cp(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var o=up(r,0,t),a=up(r,t,r.length),u=t-o,l=t-a,f=2+u+1+1+l,h=f{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.LRUCache=void 0;hr.snakeToCamel=mp;hr.originalOrCamelOptions=eb;hr.removeUndefinedValuesInObject=tb;hr.isValidFile=rb;hr.getWellKnownCertificateConfigFileLocation=nb;var XC=X("fs"),QC=X("os"),Nu=X("path"),ZC="certificate_config.json",pp="gcloud";function mp(r){return r.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function eb(r){function e(t){let n=r||{};return n[t]??n[mp(t)]}return{get:e}}var qu=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#r()}get(e){let t=this.#e.get(e);if(t)return this.#t(e,t.value),this.#r(),t.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();for(;!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed{(t===void 0||t==="undefined")&&delete r[e]}),r}async function rb(r){try{return(await XC.promises.lstat(r)).isFile()}catch{return!1}}function nb(){let r=process.env.CLOUDSDK_CONFIG||(sb()?Nu.join(process.env.APPDATA||"",pp):Nu.join(process.env.HOME||"",".config",pp));return Nu.join(r,ZC)}function sb(){return QC.platform().startsWith("win")}});var gp=z((jS,ob)=>{ob.exports={name:"google-auth-library",version:"10.2.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.1","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"^5.1.6",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var ju=z(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.USER_AGENT=xr.PRODUCT_NAME=xr.pkg=void 0;var yp=gp();xr.pkg=yp;var _p="google-api-nodejs-client";xr.PRODUCT_NAME=_p;var ib=`${_p}/${yp.version}`;xr.USER_AGENT=ib});var pt=z(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.AuthClient=Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Lt.DEFAULT_UNIVERSE=void 0;var ab=X("events"),Lu=Je(),ub=jt(),cb=Du(),Uu=ju();Lt.DEFAULT_UNIVERSE="googleapis.com";Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=5*60*1e3;var Mu=class r extends ab.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Lt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=(0,ub.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??Lt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Lu.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(r.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(r.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&Lu.Gaxios.mergeHeaders(a,t.headers),n&&Lu.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){let n=t.get("x-goog-user-project"),o=t.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,cb.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let t=e.headers.get("User-Agent");t?t.includes(`${Uu.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${Uu.USER_AGENT}`):e.headers.set("User-Agent",Uu.USER_AGENT);try{let n=e,o=n[r.RequestMethodNameSymbol],a=`${Math.floor(Math.random()*1e3)}`;n[r.RequestLogIdSymbol]=a;let u={url:e.url,headers:e.headers};o?r.log.info("%s [%s] request %j",o,a,u):r.log.info("[%s] request %j",a,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] response %j",n,o,e.data):r.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] error %j",n,o,e.response?.data):r.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,t){try{let n=e;n[r.RequestMethodNameSymbol]=t}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Lt.AuthClient=Mu});var Hu=z(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.LoginTicket=void 0;var $u=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};ai.LoginTicket=$u});var rn=z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.OAuth2Client=Kt.ClientAuthentication=Kt.CertificateFormat=Kt.CodeChallengeMethod=void 0;var Cp=Je(),lb=X("querystring"),fb=X("stream"),db=Iu(),bp=jt(),Gu=Cs(),In=pt(),hb=Hu(),Ep;(function(r){r.Plain="plain",r.S256="S256"})(Ep||(Kt.CodeChallengeMethod=Ep={}));var pr;(function(r){r.PEM="PEM",r.JWK="JWK"})(pr||(Kt.CertificateFormat=pr={}));var bs;(function(r){r.ClientSecretPost="ClientSecretPost",r.ClientSecretBasic="ClientSecretBasic",r.None="None"})(bs||(Kt.ClientAuthentication=bs={}));var Wu=class r extends In.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=pr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:t,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||bs.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+lb.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Gu.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),a=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:a}}getToken(e,t){let n=typeof e=="string"?{code:e}:e;if(t)this.getTokenAsync(n).then(o=>t(null,o.tokens,o.res),o=>t(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===bs.ClientSecretBasic){let f=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${f.toString("base64")}`)}this.clientAuthentication===bs.ClientSecretPost&&(o.client_secret=this._clientSecret);let a={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,bp.removeUndefinedValuesInObject)(o)),headers:n};In.AuthClient.setMethodName(a,"getTokenAsync");let u=await this.transporter.request(a),l=u.data;return u.data&&u.data.expires_in&&(l.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete l.expires_in),this.emit("tokens",l),{tokens:l,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let u={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,bp.removeUndefinedValuesInObject)(n))};In.AuthClient.setMethodName(u,"refreshTokenNoCache"),o=await this.transporter.request(u)}catch(u){throw u instanceof Cp.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw new Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let l=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(l)}}if(this.refreshHandler){let l=await this.processAndValidateRefreshHandler();if(l?.access_token){this.setCredentials(l);let f=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(f)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(t.refresh_token),o=n.tokens}catch(l){let f=l;throw f.response&&(f.response.status===403||f.response.status===404)&&(f.message=`Could not refresh access token: ${f.message}`),f}let a=this.credentials;a.token_type=a.token_type||"Bearer",o.refresh_token=a.refresh_token,this.credentials=o;let u=new Headers({authorization:a.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new r().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let n={...r.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(In.AuthClient.setMethodName(n,"revokeToken"),t)this.transporter.request(n).then(o=>t(null,o),t);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(t=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Cp.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.response;if(o){let a=o.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),l=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,f=o.config.data instanceof fb.Readable,h=a===401||a===403;if(!t&&h&&!f&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&h&&!f&&l){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then(n=>t(null,n),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...r.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1e3,scopes:t.scope.split(" ")},t);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=(0,Gu.hasBrowserCrypto)()?pr.JWK:pr.PEM;if(this.certificateExpiry&&e[0-9]+)/.exec(a)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let l={};switch(t){case pr.PEM:l=n.data;break;case pr.JWK:for(let h of n.data.keys)l[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${t}`)}let f=new Date;return this.certificateExpiry=u===-1?null:new Date(f.getTime()+u),this.certificateCache=l,this.certificateCacheFormat=t,{certs:l,format:t,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...r.RETRY_CONFIG,url:t};In.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,n,o,a){let u=(0,Gu.createCrypto)();a||(a=r.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(l.length!==3)throw new Error("Wrong number of segments in token: "+e);let f=l[0]+"."+l[1],h=l[2],d,_;try{d=JSON.parse(u.decodeBase64StringUtf8(l[0]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token envelope: ${l[0]}': ${S.message}`),S}if(!d)throw new Error("Can't parse token envelope: "+l[0]);try{_=JSON.parse(u.decodeBase64StringUtf8(l[1]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token payload '${l[0]}`),S}if(!_)throw new Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(t,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let E=t[d.kid];if(d.alg==="ES256"&&(h=db.joseToDer(h,"ES256").toString("base64")),!await u.verify(E,f,h))throw new Error("Invalid token signature: "+e);if(!_.iat)throw new Error("No issue time in token: "+JSON.stringify(_));if(!_.exp)throw new Error("No expiration time in token: "+JSON.stringify(_));let v=Number(_.iat);if(isNaN(v))throw new Error("iat field using invalid format");let w=Number(_.exp);if(isNaN(w))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(w>=g+a)throw new Error("Expiration time too far in future: "+JSON.stringify(_));let C=v-r.CLOCK_SKEW_SECS_,R=w+r.CLOCK_SKEW_SECS_;if(gR)throw new Error("Token used too late, "+g+" > "+R+": "+JSON.stringify(_));if(o&&o.indexOf(_.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+_.iss);if(typeof n<"u"&&n!==null){let S=_.aud,N=!1;if(n.constructor===Array?N=n.indexOf(S)>-1:N=S===n,!N)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new hb.LoginTicket(d,_)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Kt.OAuth2Client=Wu});var Ju=z(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.Compute=void 0;var pb=Je(),wp=_s(),mb=rn(),zu=class extends mb.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,t;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),t=await wp.instance(o)}catch(o){throw o instanceof pb.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=t;return t&&t.expires_in&&(n.expiry_date=new Date().getTime()+t.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:t};n=await wp.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,t.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:t.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};ui.Compute=zu});var Ku=z(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.IdTokenClient=void 0;var gb=rn(),Vu=class extends gb.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1e3}};ci.IdTokenClient=Vu});var Yu=z(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.GCPEnv=void 0;Nn.clear=yb;Nn.getEnv=_b;var Ap=_s(),mr;(function(r){r.APP_ENGINE="APP_ENGINE",r.KUBERNETES_ENGINE="KUBERNETES_ENGINE",r.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",r.COMPUTE_ENGINE="COMPUTE_ENGINE",r.CLOUD_RUN="CLOUD_RUN",r.NONE="NONE"})(mr||(Nn.GCPEnv=mr={}));var Es;function yb(){Es=void 0}async function _b(){return Es||(Es=Cb(),Es)}async function Cb(){let r=mr.NONE;return bb()?r=mr.APP_ENGINE:Eb()?r=mr.CLOUD_FUNCTIONS:await Db()?await Ab()?r=mr.KUBERNETES_ENGINE:wb()?r=mr.CLOUD_RUN:r=mr.COMPUTE_ENGINE:r=mr.NONE,r}function bb(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Eb(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function wb(){return!!process.env.K_CONFIGURATION}async function Ab(){try{return await Ap.instance("attributes/cluster-name"),!0}catch{return!1}}async function Db(){return Ap.isAvailable()}});var Xu=z((zS,Dp)=>{var li=Bn().Buffer,Sb=X("stream"),vb=X("util");function fi(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=li.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=li.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}vb.inherits(fi,Sb);fi.prototype.write=function(e){this.buffer=li.concat([this.buffer,li.from(e)]),this.emit("data",e)};fi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Dp.exports=fi});var vp=z((JS,Sp)=>{"use strict";var ws=X("buffer").Buffer,Qu=X("buffer").SlowBuffer;Sp.exports=di;function di(r,e){if(!ws.isBuffer(r)||!ws.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n{var jn=Bn().Buffer,St=X("crypto"),Rp=Iu(),Tp=X("util"),kb=`"%s" is not a valid algorithm. + Supported algorithms are: + "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,As="secret must be a string or buffer",qn="key must be a string or a buffer",Fb="key must be a string, a buffer or an object",ec=typeof St.createPublicKey=="function";ec&&(qn+=" or a KeyObject",As+="or a KeyObject");function kp(r){if(!jn.isBuffer(r)&&typeof r!="string"&&(!ec||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw Ut(qn)}function Fp(r){if(!jn.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw Ut(Fb)}function Ob(r){if(!jn.isBuffer(r)){if(typeof r=="string")return r;if(!ec||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw Ut(As)}}function tc(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Op(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t{var Mb=X("buffer").Buffer;Np.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Mb.isBuffer(e)?e.toString():JSON.stringify(e)}});var $p=z((YS,Mp)=>{var $b=Bn().Buffer,qp=Xu(),Hb=rc(),Gb=X("stream"),jp=nc(),sc=X("util");function Lp(r,e){return $b.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Wb(r,e,t){t=t||"utf8";var n=Lp(jp(r),"binary"),o=Lp(jp(e),t);return sc.format("%s.%s",n,o)}function Up(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,o=r.encoding,a=Hb(e.alg),u=Wb(e,t,o),l=a.sign(u,n);return sc.format("%s.%s",u,l)}function hi(r){var e=r.secret||r.privateKey||r.key,t=new qp(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new qp(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}sc.inherits(hi,Gb);hi.prototype.sign=function(){try{var e=Up({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};hi.sign=Up;Mp.exports=hi});var Qp=z((XS,Xp)=>{var Gp=Bn().Buffer,Hp=Xu(),zb=rc(),Jb=X("stream"),Wp=nc(),Vb=X("util"),Kb=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Yb(r){return Object.prototype.toString.call(r)==="[object Object]"}function Xb(r){if(Yb(r))return r;try{return JSON.parse(r)}catch{return}}function zp(r){var e=r.split(".",1)[0];return Xb(Gp.from(e,"base64").toString("binary"))}function Qb(r){return r.split(".",2).join(".")}function Jp(r){return r.split(".")[2]}function Zb(r,e){e=e||"utf8";var t=r.split(".")[1];return Gp.from(t,"base64").toString(e)}function Vp(r){return Kb.test(r)&&!!zp(r)}function Kp(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Wp(r);var o=Jp(r),a=Qb(r),u=zb(e);return u.verify(a,o,t)}function Yp(r,e){if(e=e||{},r=Wp(r),!Vp(r))return null;var t=zp(r);if(!t)return null;var n=Zb(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Jp(r)}}function Ln(r){r=r||{};var e=r.secret||r.publicKey||r.key,t=new Hp(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Hp(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}Vb.inherits(Ln,Jb);Ln.prototype.verify=function(){try{var e=Kp(this.signature.buffer,this.algorithm,this.key.buffer),t=Yp(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Ln.decode=Yp;Ln.isValid=Vp;Ln.verify=Kp;Xp.exports=Ln});var oc=z(Br=>{var Zp=$p(),pi=Qp(),eE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Br.ALGORITHMS=eE;Br.sign=Zp.sign;Br.verify=pi.verify;Br.decode=pi.decode;Br.isValid=pi.isValid;Br.createSign=function(e){return new Zp(e)};Br.createVerify=function(e){return new pi(e)}});var pm=z(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.GoogleToken=void 0;var em=mi(X("fs")),tE=Je(),rE=mi(oc()),nE=mi(X("path")),sE=X("util");function mi(r,e){if(typeof WeakMap=="function")var t=new WeakMap,n=new WeakMap;return(mi=function(a,u){if(!u&&a&&a.__esModule)return a;var l,f,h={__proto__:null,default:a};if(a===null||gr(a)!="object"&&typeof a!="function")return h;if(l=u?n:t){if(l.has(a))return l.get(a);l.set(a,h)}for(var d in a)d!=="default"&&{}.hasOwnProperty.call(a,d)&&((f=(l=Object.defineProperty)&&Object.getOwnPropertyDescriptor(a,d))&&(f.get||f.set)?l(h,d,f):h[d]=a[d]);return h})(r,e)}function gr(r){"@babel/helpers - typeof";return gr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gr(r)}function oE(r,e){cm(r,e),e.add(r)}function iE(r,e,t){cm(r,e),e.set(r,t)}function cm(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function tm(r,e,t){return r.set(Mt(r,e),t),t}function rm(r,e){return r.get(Mt(r,e))}function Mt(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function nm(r,e){for(var t=0;t3?(Z=se===de)&&(K=ue[(H=ue[4])?5:(H=3,3)],ue[4]=ue[5]=r):ue[0]<=J&&((Z=re<2&&Jde||de>se)&&(ue[4]=re,ue[5]=de,fe.n=se,H=0))}if(Z||re>1)return u;throw he=!0,de}return function(re,de,Z){if(W>1)throw TypeError("Generator is already running");for(he&&de===1&&ye(de,Z),H=de,K=Z;(e=H<2?r:K)||!he;){L||(H?H<3?(H>1&&(fe.n=-1),ye(H,K)):fe.n=K:fe.v=K);try{if(W=2,L){if(H||(re="next"),e=L[re]){if(!(e=e.call(L,K)))throw TypeError("iterator result is not an object");if(!e.done)return e;K=e.value,H<2&&(H=0)}else H===1&&(e=L.return)&&e.call(L),H<2&&(K=TypeError("The iterator does not provide a '"+re+"' method"),H=1);L=r}else if((e=(he=fe.n<0)?K:S.call(N,fe))!==u)break}catch(ue){L=r,H=1,K=ue}finally{W=1}}return{value:e,done:he}}}(P,w,g),!0),R}var u={};function l(){}function f(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),_=h.prototype=l.prototype=Object.create(d);function E(P){return Object.setPrototypeOf?Object.setPrototypeOf(P,h):(P.__proto__=h,gt(P,o,"GeneratorFunction")),P.prototype=Object.create(_),P}return f.prototype=h,gt(_,"constructor",h),gt(h,"constructor",f),f.displayName="GeneratorFunction",gt(h,o,"GeneratorFunction"),gt(_),gt(_,o,"Generator"),gt(_,n,function(){return this}),gt(_,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:a,m:E}})()}function gt(r,e,t,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}gt=function(u,l,f,h){if(l)o?o(u,l,{value:f,enumerable:!h,configurable:!h,writable:!h}):u[l]=f;else{var d=function(E,P){gt(u,E,function(v){return this._invoke(E,P,v)})};d("next",0),d("throw",1),d("return",2)}},gt(r,e,t,n)}function sm(r,e,t,n,o,a,u){try{var l=r[a](u),f=l.value}catch(h){return void t(h)}l.done?e(f):Promise.resolve(f).then(n,o)}function Un(r){return function(){var e=this,t=arguments;return new Promise(function(n,o){var a=r.apply(e,t);function u(f){sm(a,n,o,u,l,"next",f)}function l(f){sm(a,n,o,u,l,"throw",f)}u(void 0)})}}var om=em.readFile?(0,sE.promisify)(em.readFile):Un(yt().m(function r(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new vs("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},r)})),im="https://oauth2.googleapis.com/token",pE="https://oauth2.googleapis.com/revoke?token=",vs=function(r){function e(t,n){var o;return fm(this,e),o=aE(this,e,[t]),mt(o,"code",void 0),o.code=n,o}return lE(e,r),lm(e)}(ic(Error)),Ss=new WeakMap,Yt=new WeakSet,ZS=gi.GoogleToken=function(){function r(e){fm(this,r),oE(this,Yt),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,tE.request)(n)}}),iE(this,Ss,void 0),Mt(Yt,this,hm).call(this,e)}return lm(r,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var t=new Date().getTime();return this.rawToken&&this.expiresAt?t>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var t,n=new Date().getTime(),o=(t=this.eagerRefreshThresholdMillis)!==null&&t!==void 0?t:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(gr(t)==="object"&&(n=t,t=void 0),n=Object.assign({forceRefresh:!1},n),t){var o=t;Mt(Yt,this,am).call(this,n).then(function(a){return o(null,a)},t);return}return Mt(Yt,this,am).call(this,n)}},{key:"getCredentials",value:function(){var e=Un(yt().m(function n(o){var a,u,l,f,h,d,_;return yt().w(function(E){for(;;)switch(E.n){case 0:a=nE.extname(o),_=a,E.n=_===".json"?1:_===".der"||_===".crt"||_===".pem"?4:_===".p12"||_===".pfx"?6:7;break;case 1:return E.n=2,om(o,"utf8");case 2:if(u=E.v,l=JSON.parse(u),f=l.private_key,h=l.client_email,!(!f||!h)){E.n=3;break}throw new vs("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return E.a(2,{privateKey:f,clientEmail:h});case 4:return E.n=5,om(o,"utf8");case 5:return d=E.v,E.a(2,{privateKey:d});case 6:throw new vs("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new vs("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return E.a(2)}},n)}));function t(n){return e.apply(this,arguments)}return t}()},{key:"revokeToken",value:function(t){if(t){Mt(Yt,this,um).call(this).then(function(){return t()},t);return}return Mt(Yt,this,um).call(this)}}])}();function am(r){return ac.apply(this,arguments)}function ac(){return ac=Un(yt().m(function r(e){return yt().w(function(t){for(;;)switch(t.n){case 0:if(!(rm(Ss,this)&&!e.forceRefresh)){t.n=1;break}return t.a(2,rm(Ss,this));case 1:return t.p=1,t.n=2,tm(Ss,this,Mt(Yt,this,mE).call(this,e));case 2:return t.a(2,t.v);case 3:return t.p=3,tm(Ss,this,void 0),t.f(3);case 4:return t.a(2)}},r,this,[[1,,3,4]])})),ac.apply(this,arguments)}function mE(r){return uc.apply(this,arguments)}function uc(){return uc=Un(yt().m(function r(e){var t;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:t=n.v,this.key=t.privateKey,this.iss=t.clientEmail||this.iss,t.clientEmail||Mt(Yt,this,gE).call(this);case 4:return n.a(2,Mt(Yt,this,yE).call(this))}},r,this)})),uc.apply(this,arguments)}function gE(){if(!this.iss)throw new vs("email is required.","MISSING_CREDENTIALS")}function um(){return cc.apply(this,arguments)}function cc(){return cc=Un(yt().m(function r(){var e;return yt().w(function(t){for(;;)switch(t.n){case 0:if(this.accessToken){t.n=1;break}throw new Error("No token to revoke.");case 1:return e=pE+this.accessToken,t.n=2,this.transporter.request({url:e,retry:!0});case 2:Mt(Yt,this,hm).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return t.a(2)}},r,this)})),cc.apply(this,arguments)}function hm(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=r.keyFile,this.key=r.key,this.rawToken=void 0,this.iss=r.email||r.iss,this.sub=r.sub,this.additionalClaims=r.additionalClaims,gr(r.scope)==="object"?this.scope=r.scope.join(" "):this.scope=r.scope,this.eagerRefreshThresholdMillis=r.eagerRefreshThresholdMillis,r.transporter&&(this.transporter=r.transporter)}function yE(){return lc.apply(this,arguments)}function lc(){return lc=Un(yt().m(function r(){var e,t,n,o,a,u,l,f,h,d;return yt().w(function(_){for(;;)switch(_.n){case 0:return e=Math.floor(new Date().getTime()/1e3),t=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:im,exp:e+3600,iat:e,sub:this.sub},t),o=rE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),_.p=1,_.n=2,this.transporter.request({method:"POST",url:im,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return a=_.v,this.rawToken=a.data,this.expiresAt=a.data.expires_in===null||a.data.expires_in===void 0?void 0:(e+a.data.expires_in)*1e3,_.a(2,this.rawToken);case 3:throw _.p=3,d=_.v,this.rawToken=void 0,this.tokenExpires=void 0,f=d.response&&(u=d.response)!==null&&u!==void 0&&u.data?(l=d.response)===null||l===void 0?void 0:l.data:{},f.error&&(h=f.error_description?": ".concat(f.error_description):"",d.message="".concat(f.error).concat(h)),d;case 4:return _.a(2)}},r,this,[[1,3]])})),lc.apply(this,arguments)}});var hc=z(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.JWTAccess=void 0;var _E=oc(),CE=jt(),mm={alg:"RS256",typ:"JWT"},dc=class r{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new CE.LRUCache({capacity:500,maxAge:60*60*1e3});constructor(e,t,n,o){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=o??5*60*1e3}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length?n=e?`${e}_${t.join("_")}`:`${t.join("_")}`:typeof t=="string"&&(n=e?`${e}_${t}`:t),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,t,n){let o=this.getCachedKey(e,n),a=this.cache.get(o),u=Date.now();if(a&&a.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(a.headers);let l=Math.floor(Date.now()/1e3),f=r.getExpirationTime(l),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:f,iat:l}:h={iss:this.email,sub:this.email,aud:e,exp:f,iat:l},t){for(let v in h)if(t[v])throw new Error(`The '${v}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...mm,kid:this.keyId}:mm,_=Object.assign(h,t),E=_E.sign({header:d,payload:_,secret:this.key}),P=new Headers({authorization:`Bearer ${E}`});return this.cache.set(o,{expiration:f*1e3,headers:P}),P}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",a=>o+=a).on("error",n).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}};yi.JWTAccess=dc});var mc=z(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.JWT=void 0;var gm=pm(),bE=hc(),EE=rn(),_i=pt(),pc=class r extends EE.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new r(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==_i.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==_i.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${_i.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new bE.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==_i.DEFAULT_UNIVERSE,a=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(a)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let t=new gm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw new Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(t=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new gm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let t=await this.createGToken().getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ci.JWT=pc});var yc=z(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.UserRefreshClient=Mn.USER_REFRESH_ACCOUNT_TYPE=void 0;var wE=rn(),AE=pt();Mn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var gc=class r extends wE.OAuth2Client{_refreshToken;constructor(e,t,n,o,a){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:a};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...r.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return AE.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);return this.fromJSON(a),t()}catch(a){return n(a)}})})}static fromJSON(e){let t=new r;return t.fromJSON(e),t}};Mn.UserRefreshClient=gc});var Cc=z($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.Impersonated=$n.IMPERSONATED_ACCOUNT_TYPE=void 0;var ym=rn(),DE=Je(),SE=jt();$n.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var _c=class r extends ym.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new ym.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,SE.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${t}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...r.RETRY_CONFIG,url:t,data:n,method:"POST"}),a=o.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";throw e instanceof DE.GaxiosError&&(t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),t&&n?(e.message=`${t}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,a={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:o,data:a,method:"POST"})).data.token}};$n.Impersonated=_c});var Ec=z(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.OAuthClientAuthHandler=void 0;ks.getErrorFromOAuthErrorResponse=RE;var Hn=Je(),vE=Cs(),TE=["PUT","POST","PATCH"],bc=class{#e=(0,vE.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Hn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Hn.Gaxios)}applyClientAuthenticationOptions(e,t){e.headers=Hn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),t||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=Hn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Hn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",a=this.#e.encodeBase64StringUtf8(`${n}:${o}`);Hn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${a}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!TE.includes(t))throw new Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let a=new URLSearchParams(e.data??"");a.append("client_id",this.#t.clientId),a.append("client_secret",this.#t.clientSecret||""),e.data=a}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};ks.OAuthClientAuthHandler=bc;function RE(r,e){let t=r.error,n=r.error_description,o=r.error_uri,a=`Error code ${t}`;typeof n<"u"&&(a+=`: ${n}`),typeof o<"u"&&(a+=` - ${o}`);let u=new Error(a);if(e){let l=Object.keys(e);e.stack&&l.push("stack"),l.forEach(f=>{f!=="message"&&Object.defineProperty(u,f,{value:e[f],writable:!1,enumerable:!0})})}return u}});var Ei=z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.StsCredentials=void 0;var kE=Je(),FE=pt(),_m=Ec(),OE=jt(),wc=class r extends _m.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,n){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},a={...r.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams((0,OE.removeUndefinedValuesInObject)(o))};FE.AuthClient.setMethodName(a,"exchangeToken"),this.applyClientAuthenticationOptions(a);try{let u=await this.transporter.request(a),l=u.data;return l.res=u,l}catch(u){throw u instanceof kE.GaxiosError&&u.response?(0,_m.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};bi.StsCredentials=wc});var Ir=z(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.BaseExternalAccountClient=vt.CLOUD_RESOURCE_MANAGER=vt.EXTERNAL_ACCOUNT_TYPE=vt.EXPIRATION_TIME_OFFSET=void 0;var PE=Je(),xE=X("stream"),Ac=pt(),BE=Ei(),Cm=jt(),IE=ju(),NE="urn:ietf:params:oauth:grant-type:token-exchange",qE="urn:ietf:params:oauth:token-type:access_token",Dc="https://www.googleapis.com/auth/cloud-platform",jE=3600;vt.EXPIRATION_TIME_OFFSET=5*60*1e3;vt.EXTERNAL_ACCOUNT_TYPE="external_account";vt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var LE="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",UE="https://sts.{universeDomain}/v1/token",Sc=class r extends Ac.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=(0,Cm.originalOrCamelOptions)(e),n=t.get("type");if(n&&n!==vt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${vt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=t.get("client_id"),a=t.get("client_secret");this.tokenUrl=t.get("token_url")??UE.replace("{universeDomain}",this.universeDomain);let u=t.get("subject_token_type"),l=t.get("workforce_pool_user_project"),f=t.get("service_account_impersonation_url"),h=t.get("service_account_impersonation"),d=(0,Cm.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:a}),this.stsCredential=new BE.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[Dc],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=l;let _=new RegExp(LE);if(this.workforcePoolUserProject&&!this.audience.match(_))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=f,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=jE),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let t=await this.getRequestHeaders(),n={...r.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`};Ac.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=PE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof xE.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:NE,audience:this.audience,requestedTokenType:qE,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Dc]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),a=await this.stsCredential.exchangeToken(t,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(a.access_token):a.expires_in?this.cachedAccessToken={access_token:a.access_token,expiry_date:new Date().getTime()+a.expires_in*1e3,res:a.res}:this.cachedAccessToken={access_token:a.access_token,res:a.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let t={...r.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Ac.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let n=await this.transporter.request(t),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Dc]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${IE.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};vt.BaseExternalAccountClient=Sc});var bm=z(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.FileSubjectTokenSupplier=void 0;var Tc=X("util"),Rc=X("fs"),ME=(0,Tc.promisify)(Rc.readFile??(()=>{})),$E=(0,Tc.promisify)(Rc.realpath??(()=>{})),HE=(0,Tc.promisify)(Rc.lstat??(()=>{})),vc=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await $E(e),!(await HE(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let t,n=await ME(e,{encoding:"utf8"});if(this.formatType==="text"?t=n:this.formatType==="json"&&this.subjectTokenFieldName&&(t=JSON.parse(n)[this.subjectTokenFieldName]),!t)throw new Error("Unable to parse the subject_token from the credential_source file");return t}};wi.FileSubjectTokenSupplier=vc});var Em=z(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.UrlSubjectTokenSupplier=void 0;var GE=pt(),kc=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};GE.AuthClient.setMethodName(t,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(t)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(t)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Ai.UrlSubjectTokenSupplier=kc});var wm=z(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Di=jt(),Si=X("fs"),vi=X("crypto"),WE=X("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Xt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=Xt;var Tt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=Tt;var Fc=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Tt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Tt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Tt("Cannot create mTLS Agent with missing certificate or key");return new WE.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,t),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Di.isValidFile)(e))return e;throw new Xt(`Provided certificate config path is invalid: ${e}`)}let t=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await(0,Di.isValidFile)(t))return t;throw new Xt(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let n=(0,Di.getWellKnownCertificateConfigFileLocation)();if(await(0,Di.isValidFile)(n))return n;throw new Xt(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await Si.promises.readFile(e,"utf8")}catch{throw new Xt(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),o=n?.cert_configs?.workload?.cert_path,a=n?.cert_configs?.workload?.key_path;if(!o||!a)throw new Tt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:a}}catch(n){throw n instanceof Tt?n:new Tt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,t){let n,o;try{n=await Si.promises.readFile(e),new vi.X509Certificate(n)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Xt(`Failed to read certificate file at ${e}: ${u}`)}try{o=await Si.promises.readFile(t),(0,vi.createPrivateKey)(o)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Xt(`Failed to read private key file at ${t}: ${u}`)}return{cert:n,key:o}}async#n(e){let t=new vi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let a=((await Si.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((f,h)=>{try{return new vi.X509Certificate(f)}catch(d){let _=d instanceof Error?d.message:String(d);throw new Tt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${_}`)}}),u=a.findIndex(f=>t.raw.equals(f.raw)),l;if(u===-1)l=[t,...a];else if(u===0)l=a;else throw new Tt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(l.map(f=>f.raw.toString("base64")))}catch(n){if(n instanceof Tt)throw n;let o=n instanceof Error?n.message:String(n);throw new Xt(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};_t.CertificateSubjectTokenSupplier=Fc});var xc=z(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.IdentityPoolClient=void 0;var zE=Ir(),Oc=jt(),JE=bm(),VE=Em(),Am=wm(),KE=Ei(),Dm=Je(),Pc=class r extends zE.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=(0,Oc.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let a=(0,Oc.originalOrCamelOptions)(n),u=(0,Oc.originalOrCamelOptions)(a.get("format")),l=u.get("type")||"text",f=u.get("subject_token_field_name");if(l!=="json"&&l!=="text")throw new Error(`Invalid credential_source format "${l}"`);if(l==="json"&&!f)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=a.get("file"),d=a.get("url"),_=a.get("certificate"),E=a.get("headers");if(h&&d||d&&_||h&&_)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new JE.FileSubjectTokenSupplier({filePath:h,formatType:l,subjectTokenFieldName:f});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new VE.UrlSubjectTokenSupplier({url:d,formatType:l,subjectTokenFieldName:f,headers:E,additionalGaxiosOptions:r.RETRY_CONFIG});else if(_){this.credentialSourceType="certificate";let P=new Am.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:_.use_default_certificate_config,certificateConfigLocation:_.certificate_config_location,trustChainPath:_.trust_chain_path});this.subjectTokenSupplier=P}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Am.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new KE.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Dm.Gaxios({agent:t})}),this.transporter=new Dm.Gaxios({...this.transporter.defaults||{},agent:t})}return e}};Ti.IdentityPoolClient=Pc});var Ic=z(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.AwsRequestSigner=void 0;var Ri=Je(),vm=Cs(),Sm="AWS4-HMAC-SHA256",YE="aws4_request",Bc=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,vm.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let t=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",a=e.body||t,u=e.headers,l=await this.getCredentials(),f=new URL(n);if(typeof a!="string"&&a!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let h=await QE({crypto:this.crypto,host:f.host,canonicalUri:f.pathname,canonicalQuerystring:f.search.slice(1),method:o,region:this.region,securityCredentials:l,requestPayload:a,additionalAmzHeaders:u}),d=Ri.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:f.host},u||{});l.token&&Ri.Gaxios.mergeHeaders(d,{"x-amz-security-token":l.token});let _={url:n,method:o,headers:d};return a!==void 0&&(_.body=a),_}};ki.AwsRequestSigner=Bc;async function Fs(r,e,t){return await r.signWithHmacSha256(e,t)}async function XE(r,e,t,n,o){let a=await Fs(r,`AWS4${e}`,t),u=await Fs(r,a,n),l=await Fs(r,u,o);return await Fs(r,l,"aws4_request")}async function QE(r){let e=Ri.Gaxios.mergeHeaders(r.additionalAmzHeaders),t=r.requestPayload||"",n=r.host.split(".")[0],o=new Date,a=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");r.securityCredentials.token&&e.set("x-amz-security-token",r.securityCredentials.token);let l=Ri.Gaxios.mergeHeaders({host:r.host},e.has("date")?{}:{"x-amz-date":a},e),f="",h=[...l.keys()].sort();h.forEach(R=>{f+=`${R}:${l.get(R)} +`});let d=h.join(";"),_=await r.crypto.sha256DigestHex(t),E=`${r.method.toUpperCase()} +${r.canonicalUri} +${r.canonicalQuerystring} +${f} +${d} +${_}`,P=`${u}/${r.region}/${n}/${YE}`,v=`${Sm} +${a} +${P} +`+await r.crypto.sha256DigestHex(E),w=await XE(r.crypto,r.securityCredentials.secretAccessKey,u,r.region,n),g=await Fs(r.crypto,w,v),C=`${Sm} Credential=${r.securityCredentials.accessKeyId}/${P}, SignedHeaders=${d}, Signature=${(0,vm.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:a,authorizationHeader:C,canonicalQuerystring:r.canonicalQuerystring}}});var Tm=z(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.DefaultAwsSecurityCredentialsSupplier=void 0;var Fi=pt(),Nc=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let t=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:t};Fi.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(t,e.transporter),o=await this.#r(n,t,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Fi.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Fi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await t.request(n)).data}async#r(e,t,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t};return Fi.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Oi.DefaultAwsSecurityCredentialsSupplier=Nc});var jc=z(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.AwsClient=void 0;var ZE=Ic(),ew=Ir(),tw=Tm(),Rm=jt(),rw=Je(),qc=class r extends ew.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let t=(0,Rm.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=r.#e,this.credentialSourceType="programmatic";else{let a=(0,Rm.originalOrCamelOptions)(n);this.environmentId=a.get("environment_id");let u=a.get("region_url"),l=a.get("url"),f=a.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new tw.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:l,imdsV2SessionTokenUrl:f}),this.regionalCredVerificationUrl=a.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new ZE.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...r.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return rw.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,a)=>t.push({key:a,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}};Pi.AwsClient=qc});var Hc=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.InvalidSubjectTokenError=qe.InvalidMessageFieldError=qe.InvalidCodeFieldError=qe.InvalidTokenTypeFieldError=qe.InvalidExpirationTimeFieldError=qe.InvalidSuccessFieldError=qe.InvalidVersionFieldError=qe.ExecutableResponseError=qe.ExecutableResponse=void 0;var xi="urn:ietf:params:oauth:token-type:saml2",Lc="urn:ietf:params:oauth:token-type:id_token",Uc="urn:ietf:params:oauth:token-type:jwt",Mc=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Bi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Ii("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==xi&&this.tokenType!==Lc&&this.tokenType!==Uc)throw new Ni(`Executable response must contain a 'token_type' field when successful and it must be one of ${Lc}, ${Uc}, or ${xi}.`);if(this.tokenType===xi){if(!e.saml_response)throw new Os(`Executable response must contain a 'saml_response' field when token_type=${xi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Os(`Executable response must contain a 'id_token' field when token_type=${Lc} or ${Uc}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new qi("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ji("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.PluggableAuthHandler=Gn.ExecutableError=void 0;var nn=Hc(),nw=X("child_process"),Gc=X("fs"),Li=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};Gn.ExecutableError=Li;var Wc=class r{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=r.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,n)=>{let o=nw.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",l=>{a+=l}),o.stderr.on("data",l=>{a+=l});let u=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",l=>{if(clearTimeout(u),l===0)try{let f=JSON.parse(a),h=new nn.ExecutableResponse(f);return t(h)}catch(f){return f instanceof nn.ExecutableResponseError?n(f):n(new nn.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}else return n(new Li(a,l.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Gc.promises.realpath(this.outputFile)}catch{return}if(!(await Gc.promises.lstat(e)).isFile())return;let t=await Gc.promises.readFile(e,{encoding:"utf8"});if(t!=="")try{let n=JSON.parse(t);return new nn.ExecutableResponse(n).isValid()?new nn.ExecutableResponse(n):void 0}catch(n){throw n instanceof nn.ExecutableResponseError?n:new nn.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.PluggableAuthClient=Wn.ExecutableError=void 0;var sw=Ir(),ow=Hc(),km=zc(),iw=zc();Object.defineProperty(Wn,"ExecutableError",{enumerable:!0,get:function(){return iw.ExecutableError}});var aw=30*1e3,Fm=5*1e3,Om=120*1e3,uw="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Pm=1,Jc=class extends sw.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=aw;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillisOm)throw new Error(`Timeout must be between ${Fm} and ${Om} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new km.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[uw]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>Pm)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Pm}.`);if(!e.success)throw new km.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new ow.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};Wn.PluggableAuthClient=Jc});var Yc=z(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.ExternalAccountClient=void 0;var cw=Ir(),lw=xc(),fw=jc(),dw=Vc(),Kc=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===cw.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new fw.AwsClient(e):e.credential_source?.executable?new dw.PluggableAuthClient(e):new lw.IdentityPoolClient(e):null}};Ui.ExternalAccountClient=Kc});var Nm=z(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.ExternalAccountAuthorizedUserClient=zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Bm=pt(),xm=Ec(),Im=Je(),hw=X("stream"),pw=Ir();zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var mw="https://sts.{universeDomain}/v1/oauthtoken",Xc=class r extends xm.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let n={...r.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Bm.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),a=o.data;return a.res=o,a}catch(o){throw o instanceof Im.GaxiosError&&o.response?(0,xm.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Qc=class extends Bm.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Xc({tokenRefreshEndpoint:e.token_url??mw.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=pw.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Im.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof hw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};zn.ExternalAccountAuthorizedUserClient=Qc});var Um=z($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.GoogleAuth=$t.GoogleAuthExceptionMessages=void 0;var gw=X("child_process"),Ps=X("fs"),yw=Je(),xs=_s(),_w=X("os"),Zc=X("path"),Cw=Cs(),bw=Ju(),Ew=Ku(),ww=Yu(),Jn=mc(),qm=yc(),Vn=Cc(),Aw=Yc(),Bs=Ir(),el=pt(),jm=Nm(),Lm=jt();$t.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment. +To learn more about Universe Domain retrieval, visit: +https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var tl=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError($t.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(t=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===$t.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error($t.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await xs.universe("universe-domain"),e||=el.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=el.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,Lm.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=el.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e=="function"?t=e:n=e,t)this.getApplicationDefaultAsync(n).then(o=>t(null,o.credential,o.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t)return t instanceof Jn.JWT?t.scopes=this.scopes:t instanceof Bs.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t)return t instanceof Jn.JWT?t.scopes=this.scopes:t instanceof Bs.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new bw.Compute(e));throw new Error($t.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=xs.getGCPResidency()||await xs.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let o=process.env.HOME;o&&(t=Zc.join(o,".config"))}return t&&(t=Zc.join(t,"gcloud","application_default_credentials.json"),Ps.existsSync(t)||(t=null)),t?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ps.realpathSync(e),!Ps.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=Ps.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Vn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Vn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Vn.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,t={}){let n,o=(0,Lm.originalOrCamelOptions)(t).get("universe_domain");return e.type===qm.USER_REFRESH_ACCOUNT_TYPE?(n=new qm.UserRefreshClient(t),n.fromJSON(e)):e.type===Vn.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Bs.EXTERNAL_ACCOUNT_TYPE?(n=Aw.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes()):e.type===jm.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new jm.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,n=new Jn.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let o={};if(typeof t=="function"?n=t:o=t,n)this.fromStreamAsync(e,o).then(a=>n(null,a),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,t){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let a=[];e.setEncoding("utf8").on("error",o).on("data",u=>a.push(u)).on("end",()=>{try{try{let u=JSON.parse(a.join("")),l=this._cacheClientFromJSON(u,t);return n(l)}catch(u){if(!this.keyFilename)throw u;let l=new Jn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=l,this.setGapicJWTValues(l),n(l)}}catch(u){return o(u)}})})}fromAPIKey(e,t={}){return new Jn.JWT({...t,apiKey:e})}_isWindows(){let e=_w.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,gw.exec)("gcloud config config-helper --format json",(t,n)=>{if(!t&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Bs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await xs.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(t=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Vn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Bs.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[t,n]=await Promise.all([xs.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:n}}throw new Error($t.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Zc.resolve(this.keyFilename),t=Ps.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new Ew.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,o=await(await this.getClient()).getRequestHeaders(t);return e.headers=yw.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,ww.getEnv)()}async sign(e,t){let n=await this.getClient(),o=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof Vn.Impersonated)return(await n.sign(e)).signedBlob;let a=(0,Cw.createCrypto)();if(n instanceof Jn.JWT&&n.key)return await a.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(a,u.client_email,e,t)}async signBlob(e,t,n,o){let a=new URL(o+`${t}:signBlob`);return(await this.request({method:"POST",url:a.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};$t.GoogleAuth=tl});var Mm=z(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.IAMAuth=void 0;var rl=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Mi.IAMAuth=rl});var $m=z(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.DownscopedClient=Zt.EXPIRATION_TIME_OFFSET=Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Dw=Je(),Sw=X("stream"),nl=pt(),vw=Ei(),Tw="urn:ietf:params:oauth:grant-type:token-exchange",Rw="urn:ietf:params:oauth:token-type:access_token",kw="urn:ietf:params:oauth:token-type:access_token";Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Zt.EXPIRATION_TIME_OFFSET=5*60*1e3;var sl=class extends nl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof nl.AuthClient?{}:e),e instanceof nl.AuthClient?(this.authClient=e,this.credentialAccessBoundary=t):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new vw.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Dw.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof Sw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:Tw,requestedTokenType:Rw,subjectToken:e,subjectTokenType:kw},n=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,a=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:a,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Zt.DownscopedClient=sl});var Hm=z($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.PassThroughClient=void 0;var Fw=pt(),ol=class extends Fw.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};$i.PassThroughClient=ol});var al=z(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.GoogleAuth=ee.auth=ee.PassThroughClient=ee.ExecutableError=ee.PluggableAuthClient=ee.DownscopedClient=ee.BaseExternalAccountClient=ee.ExternalAccountClient=ee.IdentityPoolClient=ee.AwsRequestSigner=ee.AwsClient=ee.UserRefreshClient=ee.LoginTicket=ee.ClientAuthentication=ee.OAuth2Client=ee.CodeChallengeMethod=ee.Impersonated=ee.JWT=ee.JWTAccess=ee.IdTokenClient=ee.IAMAuth=ee.GCPEnv=ee.Compute=ee.DEFAULT_UNIVERSE=ee.AuthClient=ee.gaxios=ee.gcpMetadata=void 0;var Gm=Um();Object.defineProperty(ee,"GoogleAuth",{enumerable:!0,get:function(){return Gm.GoogleAuth}});ee.gcpMetadata=_s();ee.gaxios=Je();var Wm=pt();Object.defineProperty(ee,"AuthClient",{enumerable:!0,get:function(){return Wm.AuthClient}});Object.defineProperty(ee,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Wm.DEFAULT_UNIVERSE}});var Ow=Ju();Object.defineProperty(ee,"Compute",{enumerable:!0,get:function(){return Ow.Compute}});var Pw=Yu();Object.defineProperty(ee,"GCPEnv",{enumerable:!0,get:function(){return Pw.GCPEnv}});var xw=Mm();Object.defineProperty(ee,"IAMAuth",{enumerable:!0,get:function(){return xw.IAMAuth}});var Bw=Ku();Object.defineProperty(ee,"IdTokenClient",{enumerable:!0,get:function(){return Bw.IdTokenClient}});var Iw=hc();Object.defineProperty(ee,"JWTAccess",{enumerable:!0,get:function(){return Iw.JWTAccess}});var Nw=mc();Object.defineProperty(ee,"JWT",{enumerable:!0,get:function(){return Nw.JWT}});var qw=Cc();Object.defineProperty(ee,"Impersonated",{enumerable:!0,get:function(){return qw.Impersonated}});var il=rn();Object.defineProperty(ee,"CodeChallengeMethod",{enumerable:!0,get:function(){return il.CodeChallengeMethod}});Object.defineProperty(ee,"OAuth2Client",{enumerable:!0,get:function(){return il.OAuth2Client}});Object.defineProperty(ee,"ClientAuthentication",{enumerable:!0,get:function(){return il.ClientAuthentication}});var jw=Hu();Object.defineProperty(ee,"LoginTicket",{enumerable:!0,get:function(){return jw.LoginTicket}});var Lw=yc();Object.defineProperty(ee,"UserRefreshClient",{enumerable:!0,get:function(){return Lw.UserRefreshClient}});var Uw=jc();Object.defineProperty(ee,"AwsClient",{enumerable:!0,get:function(){return Uw.AwsClient}});var Mw=Ic();Object.defineProperty(ee,"AwsRequestSigner",{enumerable:!0,get:function(){return Mw.AwsRequestSigner}});var $w=xc();Object.defineProperty(ee,"IdentityPoolClient",{enumerable:!0,get:function(){return $w.IdentityPoolClient}});var Hw=Yc();Object.defineProperty(ee,"ExternalAccountClient",{enumerable:!0,get:function(){return Hw.ExternalAccountClient}});var Gw=Ir();Object.defineProperty(ee,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Gw.BaseExternalAccountClient}});var Ww=$m();Object.defineProperty(ee,"DownscopedClient",{enumerable:!0,get:function(){return Ww.DownscopedClient}});var zm=Vc();Object.defineProperty(ee,"PluggableAuthClient",{enumerable:!0,get:function(){return zm.PluggableAuthClient}});Object.defineProperty(ee,"ExecutableError",{enumerable:!0,get:function(){return zm.ExecutableError}});var zw=Hm();Object.defineProperty(ee,"PassThroughClient",{enumerable:!0,get:function(){return zw.PassThroughClient}});var Jw=new Gm.GoogleAuth;ee.auth=Jw});import eA from"fastify";import tA from"@fastify/cors";var Nf=zr(Ma(),1);import{readFileSync as t0,existsSync as Bf}from"fs";import{join as If}from"path";import{config as r0}from"dotenv";var mo=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:If(process.cwd(),this.options.jsonPath);if(Bf(e))try{let t=t0(e,"utf-8"),n=Nf.default.parse(t);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:If(process.cwd(),this.options.envPath);if(Bf(e))try{let t=r0({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let n=this.config[e];return n!==void 0?n:t}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(r,e=500,t="internal_error",n="api_error"){let o=new Error(r);return o.statusCode=e,o.code=t,o.type=n,o}async function qf(r,e,t){e.log.error(r);let n=r.statusCode||500,o={error:{message:r.message+r.stack||"Internal Server Error",type:r.type||"api_error",code:r.code||"internal_error"}};return t.code(n).send(o)}import{ProxyAgent as n0}from"undici";function jf(r,e,t,n){let o=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([f,h])=>{h&&o.set(f,h)});let a,u=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let f=new AbortController,h=()=>f.abort();t.signal.addEventListener("abort",h),u.addEventListener("abort",h),a=f.signal}else a=u;let l={method:"POST",headers:o,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(l.dispatcher=new n0(new URL(t.httpsProxy).toString())),n?.debug({request:l,headers:Object.fromEntries(o.entries()),requestUrl:typeof r=="string"?r:r.toString(),useProxy:t.httpsProxy},"final request"),fetch(typeof r=="string"?r:r.toString(),l)}var Lf="1.0.28";async function o0(r,e,t,n){let o=r.body,a=r.provider,u=t._server.providerService.getProvider(a);if(!u)throw nt(`Provider '${a}' not found`,404,"provider_not_found");let{requestBody:l,config:f,bypass:h}=await i0(o,u,n,r.headers),d=await u0(l,f,u,t,h,n),_=await c0(l,d,u,n,h);return l0(_,e,o)}async function i0(r,e,t,n){let o=r,a={},u=!1;if(u=a0(e,t,r),u&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!u&&typeof t.transformRequestOut=="function"){let l=await t.transformRequestOut(o);l.body?(o=l.body,a=l.config||{}):o=l}if(!u&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(o,e);f.body?(o=f.body,a={...a,...f.config}):o=f}if(!u&&e.transformer?.[r.model]?.use?.length)for(let l of e.transformer[r.model].use)!l||typeof l.transformRequestIn!="function"||(o=await l.transformRequestIn(o,e));return{requestBody:o,config:a,bypass:u}}function a0(r,e,t){return r.transformer?.use?.length===1&&r.transformer.use[0].name===e.name&&(!r.transformer?.[t.model]?.use.length||r.transformer?.[t.model]?.use.length===1&&r.transformer?.[t.model]?.use[0].name===e.name)}async function u0(r,e,t,n,o,a){let u=e.url||new URL(t.baseUrl);if(o&&typeof a.auth=="function"){let f=await a.auth(r,t);if(f.body){r=f.body;let h=e.headers||{};f.config?.headers&&(h={...h,...f.config.headers},delete h.host,delete f.config.headers),e={...e,...f.config,headers:h}}else r=f}let l=await jf(u,r,{httpsProxy:n._server.configService.getHttpsProxy(),...e,headers:{Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}}},n.log);if(!l.ok){let f=await l.text();throw nt(`Error from provider(${t.name},${r.model}: ${l.status}): ${f}`,l.status,"provider_response_error")}return l}async function c0(r,e,t,n,o){let a=e;if(!o&&t.transformer?.use?.length)for(let u of Array.from(t.transformer.use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));if(!o&&t.transformer?.[r.model]?.use?.length)for(let u of Array.from(t.transformer[r.model].use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a)),a}function l0(r,e,t){return r.ok||e.code(r.status),t.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(r.body)):r.json()}var Uf=async r=>{r.get("/",async()=>({message:"LLMs API",version:Lf})),r.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=r._server.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&r.post(t.endPoint,async(n,o)=>o0(n,o,r,t));r.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,n)=>{let{name:o,baseUrl:a,apiKey:u,models:l}=t.body;if(!o?.trim())throw nt("Provider name is required",400,"invalid_request");if(!a||!f0(a))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!l||!Array.isArray(l)||l.length===0)throw nt("At least one model is required",400,"invalid_request");if(r._server.providerService.getProvider(t.body.name))throw nt(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return r._server.providerService.registerProvider(t.body)}),r.get("/providers",async()=>r._server.providerService.getProviders()),r.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let n=r._server.providerService.getProvider(t.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),r.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(t,n)=>{let o=r._server.providerService.updateProvider(t.params.id,t.body);if(!o)throw nt("Provider not found",404,"provider_not_found");return o}),r.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!r._server.providerService.deleteProvider(t.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),r.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,n)=>{if(!r._server.providerService.toggleProvider(t.params.id,t.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})};function f0(r){try{return new URL(r),!0}catch{return!1}}var go=class{constructor(e){this.providerService=e}registerProvider(e){return this.providerService.registerProvider(e)}getProviders(){return this.providerService.getProviders()}getProvider(e){return this.providerService.getProvider(e)}updateProvider(e,t){return this.providerService.updateProvider(e,t)}deleteProvider(e){return this.providerService.deleteProvider(e)}toggleProvider(e,t){return this.providerService.toggleProvider(e,t)}resolveRoute(e){let t=this.providerService.resolveModelRoute(e);if(!t)throw new Error(`Model ${e} not found. Available models: ${this.getAvailableModelNames().join(", ")}`);return t}async getAvailableModels(){return{object:"list",data:this.providerService.getAvailableModels().flatMap(t=>t.models.map(n=>({id:n,object:"model",provider:t.provider,created:Math.floor(Date.now()/1e3),owned_by:t.provider})))}}getAvailableModelNames(){return this.providerService.getModelRoutes().map(e=>e.fullModel)}getModelRoutes(){return this.providerService.getModelRoutes()}};var yo=class{constructor(e,t,n){this.configService=e;this.transformerService=t;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let n={};t.transformer&&Object.keys(t.transformer).forEach(o=>{o==="use"?Array.isArray(t.transformer.use)&&(n.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[o]?.use)&&(n[o]={use:t.transformer[o].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],transformer:t.transformer?n:void 0}),this.logger.info(`${t.name} provider registered`)}catch(n){this.logger.error(`${t.name} provider registered error: ${n}`)}})}registerProvider(e){let t={...e};return this.providers.set(t.name,t),e.models.forEach(n=>{let o=`${t.name},${n}`,a={provider:t.name,model:n,fullModel:o};this.modelRoutes.set(o,a),this.modelRoutes.has(n)||this.modelRoutes.set(n,a)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let n=this.providers.get(e);if(!n)return null;let o={...n,...t,updatedAt:new Date};return this.providers.set(e,o),t.models&&(n.models.forEach(a=>{let u=`${n.id},${a}`;this.modelRoutes.delete(u),this.modelRoutes.delete(a)}),t.models.forEach(a=>{let u=`${n.name},${a}`,l={provider:n.name,model:a,fullModel:u};this.modelRoutes.set(u,l),this.modelRoutes.has(a)||this.modelRoutes.set(a,l)})),o}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(n=>{let o=`${t.name},${n}`;this.modelRoutes.delete(o),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){return!!this.providers.get(e)}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let n=this.providers.get(t.provider);return n?{provider:n,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push(n),e.push(`${t.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,n)=>{if(Array.isArray(n)){let[o,a={}]=n;t[o]=a}else t[n]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push({id:n,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${n}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}};var ze=[];for(let r=0;r<256;++r)ze.push((r+256).toString(16).slice(1));function Mf(r,e=0){return(ze[r[e+0]]+ze[r[e+1]]+ze[r[e+2]]+ze[r[e+3]]+"-"+ze[r[e+4]]+ze[r[e+5]]+"-"+ze[r[e+6]]+ze[r[e+7]]+"-"+ze[r[e+8]]+ze[r[e+9]]+"-"+ze[r[e+10]]+ze[r[e+11]]+ze[r[e+12]]+ze[r[e+13]]+ze[r[e+14]]+ze[r[e+15]]).toLowerCase()}import{randomFillSync as d0}from"crypto";var Co=new Uint8Array(256),_o=Co.length;function $a(){return _o>Co.length-16&&(d0(Co),_o=0),Co.slice(_o,_o+=16)}import{randomUUID as h0}from"crypto";var Ha={randomUUID:h0};function p0(r,e,t){if(Ha.randomUUID&&!e&&!r)return Ha.randomUUID();r=r||{};let n=r.random??r.rng?.()??$a();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[t+o]=n[o];return e}return Mf(n)}var Tr=p0;var $f=r=>r<=0?"none":r<=1024?"low":r<=8192?"medium":"high";var bo=class{name="Anthropic";endPoint="/v1/messages";async auth(e,t){return{body:e,config:{headers:{"x-api-key":t.apiKey,authorization:void 0}}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let a=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));t.push({role:"system",content:a})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach((a,u)=>{if(a.role==="user"||a.role==="assistant"){if(typeof a.content=="string"){t.push({role:a.role,content:a.content});return}if(Array.isArray(a.content)){if(a.role==="user"){let l=a.content.filter(h=>h.type==="tool_result"&&h.tool_use_id);l.length&&l.forEach((h,d)=>{let _={role:"tool",content:typeof h.content=="string"?h.content:JSON.stringify(h.content),tool_call_id:h.tool_use_id,cache_control:h.cache_control};t.push(_)});let f=a.content.filter(h=>h.type==="text"&&h.text||h.type==="image"&&h.source);f.length&&t.push({role:"user",content:f.map(h=>h?.type==="image"?{type:"image_url",image_url:{url:h.source?.type==="base64"?h.source.data:h.source.url},media_type:h.source.media_type}:h)})}else if(a.role==="assistant"){let l={role:"assistant",content:null},f=a.content.filter(d=>d.type==="text"&&d.text);f.length&&(l.content=f.map(d=>d.text).join(` +`));let h=a.content.filter(d=>d.type==="tool_use"&&d.id);h.length&&(l.tool_calls=h.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}}))),t.push(l)}return}}});let o={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(o.reasoning={effort:$f(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),a=this.convertOpenAIResponseToAnthropic(o);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e){return new ReadableStream({start:async n=>{let o=new TextEncoder,a=`msg_${Date.now()}`,u=null,l="unknown",f=!1,h=!1,d=!1,_=new Map,E=new Map,P=0,v=0,w=0,g=!1,C=!1,R=0,S=-1,N=H=>{if(!g)try{n.enqueue(H);let K=new TextDecoder().decode(H);this.logger.debug({dataStr:K},"send data")}catch(K){if(K instanceof TypeError&&K.message.includes("Controller is already closed"))g=!0;else throw this.logger.debug(`send data error: ${K.message}`),K}},j=()=>{if(!g)try{if(S>=0){let K={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(K)} + +`)),S=-1}u?(N(o.encode(`event: message_delta +data: ${JSON.stringify(u)} + +`)),u=null):N(o.encode(`event: message_delta +data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}})} + +`));let H={type:"message_stop"};N(o.encode(`event: message_stop +data: ${JSON.stringify(H)} + +`)),n.close(),g=!0}catch(H){if(H instanceof TypeError&&H.message.includes("Controller is already closed"))g=!0;else throw H}},L=null;try{L=e.getReader();let H=new TextDecoder,K="";for(;!g;){let{done:W,value:Ae}=await L.read();if(W)break;K+=H.decode(Ae,{stream:!0});let he=K.split(` +`);K=he.pop()||"";for(let fe of he){if(g||d)break;if(!fe.startsWith("data:"))continue;let ye=fe.slice(5).trim();if(this.logger.debug(`recieved data: ${ye}`),ye!=="[DONE]")try{let re=JSON.parse(ye);if(P++,this.logger.debug({response:re},"Original Response"),re.error){let Z={type:"error",message:{type:"api_error",message:JSON.stringify(re.error)}};N(o.encode(`event: error +data: ${JSON.stringify(Z)} + +`));continue}if(l=re.model||l,!f&&!g&&!d){f=!0;let Z={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};N(o.encode(`event: message_start +data: ${JSON.stringify(Z)} + +`))}let de=re.choices?.[0];if(re.usage&&(u?u.usage={input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}:u={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}}),!de)continue;if(de?.delta?.thinking&&!g&&!d){if(S>=0){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1}if(!C){let Z={type:"content_block_start",index:R,content_block:{type:"thinking",thinking:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Z)} + +`)),S=R,C=!0}if(de.delta.thinking.signature){let Z={type:"content_block_delta",index:R,delta:{type:"signature_delta",signature:de.delta.thinking.signature}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`));let ue={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ue)} + +`)),S=-1,R++}else if(de.delta.thinking.content){let Z={type:"content_block_delta",index:R,delta:{type:"thinking_delta",thinking:de.delta.thinking.content||""}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`))}}if(de?.delta?.content&&!g&&!d){if(v++,S>=0&&!h){let ue={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ue)} + +`)),S=-1}if(!h&&!d){h=!0;let Z={type:"content_block_start",index:R,content_block:{type:"text",text:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Z)} + +`)),S=R}if(!g&&!d){let Z={type:"content_block_delta",index:S,delta:{type:"text_delta",text:de.delta.content}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`))}}if(de?.delta?.annotations?.length&&!g&&!d){if(S>=0&&h){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1,h=!1}de?.delta?.annotations.forEach(Z=>{R++;let ue={type:"content_block_start",index:R,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Tr()}`,content:[{type:"web_search_result",title:Z.url_citation.title,url:Z.url_citation.url}]}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(ue)} + +`));let J={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(J)} + +`)),S=-1})}if(de?.delta?.tool_calls&&!g&&!d){w++;let Z=new Set;for(let ue of de.delta.tool_calls){if(g)break;let J=ue.index??0;if(Z.has(J))continue;if(Z.add(J),!E.has(J)){if(S>=0){let Ee={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Ee)} + +`)),S=-1}let oe=R;E.set(J,oe),R++;let Ie=ue.id||`call_${Date.now()}_${J}`,je=ue.function?.name||`tool_${J}`,G={type:"content_block_start",index:oe,content_block:{type:"tool_use",id:Ie,name:je,input:{}}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(G)} + +`)),S=oe;let pe={id:Ie,name:je,arguments:"",contentBlockIndex:oe};_.set(J,pe)}else if(ue.id&&ue.function?.name){let oe=_.get(J);oe.id.startsWith("call_")&&oe.name.startsWith("tool_")&&(oe.id=ue.id,oe.name=ue.function.name)}if(ue.function?.arguments&&!g&&!d){let oe=E.get(J);if(oe===void 0)continue;let Ie=_.get(J);Ie&&(Ie.arguments+=ue.function.arguments);try{let je={type:"content_block_delta",index:oe,delta:{type:"input_json_delta",partial_json:ue.function.arguments}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(je)} + +`))}catch{try{let G=ue.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),pe={type:"content_block_delta",index:oe,delta:{type:"input_json_delta",partial_json:G}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(pe)} + +`))}catch(G){console.error(G)}}}}}if(de?.finish_reason&&!g&&!d){if(v===0&&w===0&&console.error("Warning: No content in the stream response!"),S>=0){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1}g||(u={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[de.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}});break}}catch(re){this.logger?.error(`parseError: ${re.name} message: ${re.message} stack: ${re.stack} data: ${ye}`)}}}j()}catch(H){if(!g)try{n.error(H)}catch(K){console.error(K)}}finally{if(L)try{L.releaseLock()}catch(H){console.error(H)}}},cancel:n=>{this.logger.debug(`cancle stream: ${n}`)}})}convertOpenAIResponseToAnthropic(e){this.logger.debug({response:e},"Original OpenAI response");try{let t=e.choices[0];if(!t)throw new Error("No choices found in OpenAI response");let n=[];if(t.message.annotations){let a=`srvtoolu_${Tr()}`;n.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),n.push({type:"web_search_tool_result",tool_use_id:a,content:t.message.annotations.map(u=>({type:"web_search_result",url:u.url_citation.url,title:u.url_citation.title}))})}t.message.content&&n.push({type:"text",text:t.message.content}),t.message.tool_calls&&t.message.tool_calls.length>0&&t.message.tool_calls.forEach((a,u)=>{let l={};try{let f=a.function.arguments||"{}";typeof f=="object"?l=f:typeof f=="string"&&(l=JSON.parse(f))}catch{l={text:a.function.arguments||""}}n.push({type:"tool_use",id:a.id,name:a.function.name,input:l})});let o={id:e.id,type:"message",role:"assistant",model:e.model,content:n,stop_reason:t.finish_reason==="stop"?"end_turn":t.finish_reason==="length"?"max_tokens":t.finish_reason==="tool_calls"?"tool_use":t.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens||0,output_tokens:e.usage?.completion_tokens||0}};return this.logger.debug({result:o},"Conversion complete, final Anthropic response"),o}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Cn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function m0(r,e){r.includes("null")&&(e.nullable=!0);let t=r.filter(n=>n!=="null");if(t.length===1){let n=t[0].toUpperCase();e.type=Object.values(Cn).includes(n)?n:Cn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of t){let o=n.toUpperCase();e.anyOf.push({type:Object.values(Cn).includes(o)?o:Cn.TYPE_UNSPECIFIED})}}}function is(r){let e={},t=["items"],n=["anyOf"],o=["properties"];if(r.type&&r.anyOf)throw new Error("type and anyOf cannot be both populated.");let a=r.anyOf;a!=null&&Array.isArray(a)&&a.length==2&&(a[0]&&a[0].type==="null"?(e.nullable=!0,r=a[1]):a[1]&&a[1].type==="null"&&(e.nullable=!0,r=a[0])),r.type&&Array.isArray(r.type)&&m0(r.type,e);for(let[u,l]of Object.entries(r))if(l!=null)if(u=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(l))continue;let f=l.toUpperCase();e.type=Object.values(Cn).includes(f)?f:Cn.TYPE_UNSPECIFIED}else if(t.includes(u))e[u]=is(l);else if(n.includes(u)){let f=[];for(let h of l){if(h.type=="null"){e.nullable=!0;continue}f.push(is(h))}e[u]=f}else if(o.includes(u)){let f={};for(let[h,d]of Object.entries(l))f[h]=is(d);e[u]=f}else{if(u==="additionalProperties")continue;e[u]=l}return e}function g0(r){if(r.functionDeclarations)for(let e of r.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=is(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=is(e.response));return r}function Eo(r){let e=[],t=r.tools?.filter(u=>u.function.name!=="web_search")?.map(u=>({name:u.function.name,description:u.function.description,parametersJsonSchema:u.function.parameters}));t?.length&&e.push(g0({functionDeclarations:t})),r.tools?.find(u=>u.function.name==="web_search")&&e.push({googleSearch:{}});let a={contents:r.messages.map(u=>{let l;u.role==="assistant"?l="model":(["user","system","tool"].includes(u.role),l="user");let f=[];return typeof u.content=="string"?f.push({text:u.content}):Array.isArray(u.content)&&f.push(...u.content.map(h=>{if(h.type==="text")return{text:h.text||""};if(h.type==="image_url")return h.image_url.url.startsWith("http")?{file_data:{mime_type:h.media_type,file_uri:h.image_url.url}}:{inlineData:{mime_type:h.media_type,data:h.image_url.url}}})),Array.isArray(u.tool_calls)&&f.push(...u.tool_calls.map(h=>({functionCall:{id:h.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:h.function.name,args:JSON.parse(h.function.arguments||"{}")}}))),{role:l,parts:f}}),tools:e.length?e:void 0};if(r.tool_choice){let u={functionCallingConfig:{}};r.tool_choice==="auto"?u.functionCallingConfig.mode="auto":r.tool_choice==="none"?u.functionCallingConfig.mode="none":r.tool_choice==="required"?u.functionCallingConfig.mode="any":r.tool_choice?.function?.name&&(u.functionCallingConfig.mode="any",u.functionCallingConfig.allowedFunctionNames=[r.tool_choice?.function?.name]),a.toolConfig=u}return a}function wo(r){let e=r.contents,t=r.tools,n=r.model,o=r.max_tokens,a=r.temperature,u=r.stream,l=r.tool_choice,f={messages:[],model:n,max_tokens:o,temperature:a,stream:u,tool_choice:l};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?f.messages.push({role:"user",content:h}):typeof h.text=="string"?f.messages.push({role:"user",content:h.text||null}):h.role==="user"?f.messages.push({role:"user",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):h.role==="model"&&f.messages.push({role:"assistant",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(t)&&(f.tools=[],t.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(d=>{f.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),f}async function Ao(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o=n.candidates[0].content?.parts?.filter(u=>u.functionCall)?.map(u=>({id:u.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:u.functionCall?.name,arguments:JSON.stringify(u.functionCall?.args||{})}}))||[],a={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:n.candidates[0].content?.parts?.filter(u=>u.text)?.map(u=>u.text)?.join(` +`)||"",role:"assistant",tool_calls:o.length>0?o:void 0}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata.candidatesTokenCount,prompt_tokens:n.usageMetadata.promptTokenCount,cached_content_token_count:n.usageMetadata.cachedContentTokenCount||null,total_tokens:n.usageMetadata.totalTokenCount}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(!d.candidates||!d.candidates[0]){log("Invalid chunk structure:",h);return}let _=d.candidates[0],E=_.content?.parts||[],P=E.filter(g=>g.functionCall).map(g=>({id:g.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:g.functionCall?.name,arguments:JSON.stringify(g.functionCall?.args||{})}})),w={choices:[{delta:{role:"assistant",content:E.filter(g=>g.text).map(g=>g.text).join(` +`)||"",tool_calls:P.length>0?P:void 0},finish_reason:_.finishReason?.toLowerCase()||null,index:_.index||(P.length>0?1:0),logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.responseId||"",model:d.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usageMetadata?.candidatesTokenCount||0,prompt_tokens:d.usageMetadata?.promptTokenCount||0,cached_content_token_count:d.usageMetadata?.cachedContentTokenCount||null,total_tokens:d.usageMetadata?.totalTokenCount||0}};_?.groundingMetadata?.groundingChunks?.length&&(w.choices[0].delta.annotations=_.groundingMetadata.groundingChunks.map((g,C)=>{let R=_?.groundingMetadata?.groundingSupports?.filter(S=>S.groundingChunkIndices?.includes(C));return{type:"url_citation",url_citation:{url:g?.web?.uri||"",title:g?.web?.title||"",content:R?.[0]?.segment?.text||"",start_index:R?.[0]?.segment?.startIndex||0,end_index:R?.[0]?.segment?.endIndex||0}}})),f.enqueue(o.encode(`data: ${JSON.stringify(w)} + +`))}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}var Do=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:Eo(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=wo;async transformResponseOut(e){return Ao(e,this.name,this.logger)}};async function Vw(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>zr(al(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var Hi=class{name="vertex-gemini";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await Vw();return{body:Eo(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${a}`,"x-goog-api-key":void 0}}}}transformRequestOut=wo;async transformResponseOut(e){return Ao(e,this.name)}};var Gi=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if(g.choices?.[0]?.delta?.content&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wi=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate."}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode. +IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode. +Examples: +1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available. +2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=t?.choices[0]?.message.tool_calls[0],o=JSON.parse(n.function.arguments||"{}");t.choices[0].message.content=o.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=-1,a="",u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w,exitToolIndex:g,setExitToolIndex:C,appendExitToolResponse:R}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let S=JSON.parse(E.slice(6));if(S.choices[0]?.delta?.tool_calls?.length){let N=S.choices[0].delta.tool_calls[0];if(N.function?.name==="ExitTool"){C(N.index);return}else if(g()>-1&&N.index===g()&&N.function.arguments){R(N.function.arguments);try{let j=JSON.parse(P.exitToolResponse());S.choices=[{delta:{role:"assistant",content:j.response||""}}];let L=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(L))}catch{}return}}if(S.choices?.[0]?.delta&&Object.keys(S.choices[0].delta).length>0){let N=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(N))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,exitToolIndex:()=>o,setExitToolIndex:C=>o=C,exitToolResponse:()=>a,appendExitToolResponse:C=>a+=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var zi=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l=!1,f="",h=new ReadableStream({async start(d){let _=e.body.getReader(),E=(v,w,g)=>{let C=v.split(` +`);for(let R of C)R.trim()&&w.enqueue(g.encode(R+` +`))},P=(v,w)=>{let{controller:g,encoder:C}=w;if(v.startsWith("data: ")&&v.trim()!=="data: [DONE]"){let R=v.slice(6);try{let S=JSON.parse(R);if(S.usage&&(this.logger?.debug({usage:S.usage,hasToolCall:l},"usage"),S.choices[0].finish_reason=l?"tool_calls":"stop"),S.choices?.[0]?.finish_reason==="error"&&g.enqueue(C.encode(`data: ${JSON.stringify({error:S.choices?.[0].error})} + +`)),S.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),S.choices?.[0]?.delta?.reasoning){w.appendReasoningContent(S.choices[0].delta.reasoning);let j={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,thinking:{content:S.choices[0].delta.reasoning}}}]};j.choices?.[0]?.delta&&delete j.choices[0].delta.reasoning;let L=`data: ${JSON.stringify(j)} + +`;g.enqueue(C.encode(L));return}if(S.choices?.[0]?.delta?.content&&w.reasoningContent()&&!w.isReasoningComplete()){w.setReasoningComplete(!0);let j=Date.now().toString(),L={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,content:null,thinking:{content:w.reasoningContent(),signature:j}}}]};L.choices?.[0]?.delta&&delete L.choices[0].delta.reasoning;let H=`data: ${JSON.stringify(L)} + +`;g.enqueue(C.encode(H))}S.choices?.[0]?.delta?.reasoning&&delete S.choices[0].delta.reasoning,S.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(S.choices?.[0]?.delta?.tool_calls[0].id,10))&&S.choices?.[0]?.delta?.tool_calls.forEach(j=>{j.id=`call_${Tr()}`}),S.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0),S.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof S.choices[0].index=="number"?S.choices[0].index+=1:S.choices[0].index=1);let N=`data: ${JSON.stringify(S)} + +`;g.enqueue(C.encode(N))}catch{g.enqueue(C.encode(v+` +`))}}else g.enqueue(C.encode(v+` +`))};try{for(;;){let{done:v,value:w}=await _.read();if(v){f.trim()&&E(f,d,n);break}if(!w||w.length===0)continue;let g;try{g=t.decode(w,{stream:!0})}catch(R){console.warn("Failed to decode chunk",R);continue}if(g.length===0)continue;if(f+=g,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let R=f.split(` +`);f=R.pop()||"";for(let S of R)if(S.trim())try{P(S,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:N=>o=N,reasoningContent:()=>a,appendReasoningContent:N=>a+=N,isReasoningComplete:()=>u,setReasoningComplete:N=>u=N})}catch(N){console.error("Error processing line:",S,N),d.enqueue(n.encode(S+` +`))}continue}let C=f.split(` +`);f=C.pop()||"";for(let R of C)if(R.trim())try{P(R,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),d.enqueue(n.encode(R+` +`))}}}catch(v){console.error("Stream error:",v),d.error(v)}finally{try{_.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ji=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Vi=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l="",f=new ReadableStream({async start(h){let d=e.body.getReader(),_=(P,v,w)=>{let g=P.split(` +`);for(let C of g)C.trim()&&v.enqueue(w.encode(C+` +`))},E=(P,v)=>{let{controller:w,encoder:g}=v;if(P.startsWith("data: ")&&P.trim()!=="data: [DONE]"){let C=P.slice(6);try{let R=JSON.parse(C);if(R.error)throw new Error(JSON.stringify(R));R.choices?.[0]?.delta?.content&&!v.hasTextContent()&&v.setHasTextContent(!0),R.choices?.[0]?.delta?.tool_calls?.length&&R.choices?.[0]?.delta?.tool_calls.forEach(N=>{N.id=`call_${Tr()}`}),R.choices?.[0]?.delta?.tool_calls?.length&&v.hasTextContent()&&(typeof R.choices[0].index=="number"?R.choices[0].index+=1:R.choices[0].index=1);let S=`data: ${JSON.stringify(R)} + +`;w.enqueue(g.encode(S))}catch{w.enqueue(g.encode(P+` +`))}}else w.enqueue(g.encode(P+` +`))};try{for(;;){let{done:P,value:v}=await d.read();if(P){l.trim()&&_(l,h,n);break}if(!v||v.length===0)continue;let w;try{w=t.decode(v,{stream:!0})}catch(C){console.warn("Failed to decode chunk",C);continue}if(w.length===0)continue;if(l+=w,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let C=l.split(` +`);l=C.pop()||"";for(let R of C)if(R.trim())try{E(R,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),h.enqueue(n.encode(R+` +`))}continue}let g=l.split(` +`);l=g.pop()||"";for(let C of g)if(C.trim())try{E(C,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:R=>o=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>u,setReasoningComplete:R=>u=R})}catch(R){console.error("Error processing line:",C,R),h.enqueue(n.encode(C+` +`))}}}catch(P){console.error("Stream error:",P),h.error(P)}finally{try{d.releaseLock()}catch(P){console.error("Error releasing reader lock:",P)}h.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ki=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),e}};var eg=zr(Ma(),1);var yr=class extends Error{constructor(e,t){super(`${e} at position ${t}`),this.position=t}};function Jm(r){return/^[0-9A-Fa-f]$/.test(r)}function qr(r){return r>="0"&&r<="9"}function Vm(r){return r>=" "}function Is(r){return`,:[]/{}() ++`.includes(r)}function ul(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"}function cl(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"||r>="0"&&r<="9"}var ll=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,fl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function dl(r){return`,[]/{} ++`.includes(r)}function hl(r){return Ns(r)||Kw.test(r)}var Kw=/^[[{\w-]$/;function Km(r){return r===` +`||r==="\r"||r===" "||r==="\b"||r==="\f"}function Nr(r,e){let t=r.charCodeAt(e);return t===32||t===10||t===9||t===13}function Ym(r,e){let t=r.charCodeAt(e);return t===32||t===9||t===13}function Xm(r,e){let t=r.charCodeAt(e);return t===160||t>=8192&&t<=8202||t===8239||t===8287||t===12288}function Ns(r){return pl(r)||Yi(r)}function pl(r){return r==='"'||r==="\u201C"||r==="\u201D"}function ml(r){return r==='"'}function Yi(r){return r==="'"||r==="\u2018"||r==="\u2019"||r==="`"||r==="\xB4"}function gl(r){return r==="'"}function Kn(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=r.lastIndexOf(e);return n!==-1?r.substring(0,n)+(t?"":r.substring(n+1)):r}function Rt(r,e){let t=r.length;if(!Nr(r,t-1))return r+e;for(;Nr(r,t-1);)t--;return r.substring(0,t)+e+r.substring(t)}function Qm(r,e,t){return r.substring(0,e)+r.substring(e+t)}function Zm(r){return/[,\n][ \t\r]*$/.test(r)}var Yw={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Xw={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "};function yl(r){let e=0,t="";h(["```","[```","{```"]),a()||re(),h(["```","```]","```}"]);let o=_(",");for(o&&u(),hl(r[e])&&Zm(t)?(o||(t=Rt(t,",")),C()):o&&(t=Kn(t,","));r[e]==="}"||r[e]==="]";)e++,u();if(e>=r.length)return t;ye();function a(){u();let J=w()||g()||R()||N()||j()||H(!1)||K();return u(),J}function u(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,se=e,oe=l(J);do oe=f(),oe&&(oe=l(J));while(oe);return e>se}function l(J){let se=J?Nr:Ym,oe="";for(;;)if(se(r,e))oe+=r[e],e++;else if(Xm(r,e))oe+=" ",e++;else break;return oe.length>0?(t+=oe,!0):!1}function f(){if(r[e]==="/"&&r[e+1]==="*"){for(;e=r.length;Ie||(hl(r[e])||je?t=Rt(t,":"):Z()),a()||(Ie||je?t+="null":Z())}return r[e]==="}"?(t+="}",e++):t=Rt(t,"}"),!0}return!1}function g(){if(r[e]==="["){t+="[",e++,u(),E(",")&&u();let J=!0;for(;e0&&arguments[0]!==void 0?arguments[0]:!1,se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,oe=r[e]==="\\";if(oe&&(e++,oe=!0),Ns(r[e])){let Ie=ml(r[e])?ml:gl(r[e])?gl:Yi(r[e])?Yi:pl,je=e,G=t.length,pe='"';for(e++;;){if(e>=r.length){let Ee=W(e-1);return!J&&Is(r.charAt(Ee))?(e=je,t=t.substring(0,G),R(!0)):(pe=Rt(pe,'"'),t+=pe,!0)}if(e===se)return pe=Rt(pe,'"'),t+=pe,!0;if(Ie(r[e])){let Ee=e,er=pe.length;if(pe+='"',e++,t+=pe,u(!1),J||e>=r.length||Is(r[e])||Ns(r[e])||qr(r[e]))return S(),!0;let xe=W(Ee-1),Ne=r.charAt(xe);if(Ne===",")return e=je,t=t.substring(0,G),R(!1,xe);if(Is(Ne))return e=je,t=t.substring(0,G),R(!0);t=t.substring(0,G),e=Ee+1,pe=`${pe.substring(0,er)}\\${pe.substring(er)}`}else if(J&&dl(r[e])){if(r[e-1]===":"&&ll.test(r.substring(je+1,e+2)))for(;e=r.length?e=r.length:ue()}else pe+=Ee,e+=2}else{let Ee=r.charAt(e);Ee==='"'&&r[e-1]!=="\\"?(pe+=`\\${Ee}`,e++):Km(Ee)?(pe+=Yw[Ee],e++):(Vm(Ee)||fe(Ee),pe+=Ee,e++)}oe&&P()}}return!1}function S(){let J=!1;for(u();r[e]==="+";){J=!0,e++,u(),t=Kn(t,'"',!0);let se=t.length;R()?t=Qm(t,se,1):t=Rt(t,'"')}return J}function N(){let J=e;if(r[e]==="-"){if(e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1}for(;qr(r[e]);)e++;if(r[e]==="."){if(e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1;for(;qr(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1;for(;qr(r[e]);)e++}if(!Ae())return e=J,!1;if(e>J){let se=r.slice(J,e),oe=/^0\d/.test(se);return t+=oe?`"${se}"`:se,!0}return!1}function j(){return L("true","true")||L("false","false")||L("null","null")||L("True","true")||L("False","false")||L("None","null")}function L(J,se){return r.slice(e,e+J.length)===J?(t+=se,e+=J.length,!0):!1}function H(J){let se=e;if(ul(r[e])){for(;ese){for(;Nr(r,e-1)&&e>0;)e--;let oe=r.slice(se,e);return t+=oe==="undefined"?"null":JSON.stringify(oe),r[e]==='"'&&e++,!0}}function K(){if(r[e]==="/"){let J=e;for(e++;e0&&Nr(r,se);)se--;return se}function Ae(){return e>=r.length||Is(r[e])||Nr(r,e)}function he(J){t+=`${r.slice(J,e)}0`}function fe(J){throw new yr(`Invalid character ${JSON.stringify(J)}`,e)}function ye(){throw new yr(`Unexpected character ${JSON.stringify(r[e])}`,e)}function re(){throw new yr("Unexpected end of json string",r.length)}function de(){throw new yr("Object key expected",e)}function Z(){throw new yr("Colon expected",e)}function ue(){let J=r.slice(e,e+6);throw new yr(`Invalid unicode character "${J}"`,e)}}function Qw(r,e){return r[e]==="*"&&r[e+1]==="/"}function _l(r,e){if(!r||r.trim()===""||r==="{}")return"{}";try{return JSON.parse(r),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),r}catch(t){try{let n=eg.default.parse(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=yl(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${t.message}. JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${n.message}. JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${o.message}. \u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(r)}`),e?.debug("\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback"),"{}"}}}}var Xi=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message?.tool_calls?.length)for(let n of t.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=_l(n.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o={},a=!1,u="",l=!1,f=!1,h="",d=new ReadableStream({async start(_){let E=e.body.getReader(),P=(g,C,R)=>{let S=g.split(` +`);for(let N of S)N.trim()&&C.enqueue(R.encode(N+` +`))},v=(g,C,R)=>{let S="";try{S=_l(o.arguments||"",this.logger)}catch(H){console.error(`${H.message} ${H.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),S=o.arguments||""}let N={role:"assistant",tool_calls:[{function:{name:o.name,arguments:S},id:o.id,index:o.index,type:"function"}]},j={...g,choices:[{...g.choices[0],delta:N}]};j.choices[0].delta.content!==void 0&&delete j.choices[0].delta.content;let L=`data: ${JSON.stringify(j)} + +`;C.enqueue(R.encode(L))},w=(g,C)=>{let{controller:R,encoder:S}=C;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let N=g.slice(6);try{let j=JSON.parse(N);if(j.choices?.[0]?.delta?.tool_calls?.length){let H=j.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""},H.function?.arguments&&(H.function.arguments="");let K=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(K));return}else if(o.index===H.index){H.function?.arguments&&(o.arguments+=H.function.arguments);return}else{v(j,R,S),o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""};return}}if(j.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){v(j,R,S),o={};return}j.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof j.choices[0].index=="number"?j.choices[0].index+=1:j.choices[0].index=1);let L=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(L))}catch{R.enqueue(S.encode(g+` +`))}}else R.enqueue(S.encode(g+` +`))};try{for(;;){let{done:g,value:C}=await E.read();if(g){h.trim()&&P(h,_,n);break}if(!C||C.length===0)continue;let R;try{R=t.decode(C,{stream:!0})}catch(N){console.warn("Failed to decode chunk",N);continue}if(R.length===0)continue;if(h+=R,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let N=h.split(` +`);h=N.pop()||"";for(let j of N)if(j.trim())try{w(j,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:L=>a=L,reasoningContent:()=>u,appendReasoningContent:L=>u+=L,isReasoningComplete:()=>l,setReasoningComplete:L=>l=L})}catch(L){console.error("Error processing line:",j,L),_.enqueue(n.encode(j+` +`))}continue}let S=h.split(` +`);h=S.pop()||"";for(let N of S)if(N.trim())try{w(N,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:j=>a=j,reasoningContent:()=>u,appendReasoningContent:j=>u+=j,isReasoningComplete:()=>l,setReasoningComplete:j=>l=j})}catch(j){console.error("Error processing line:",N,j),_.enqueue(n.encode(N+` +`))}}}catch(g){console.error("Stream error:",g),_.error(g)}finally{try{E.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}_.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Qi=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(this.logger?.debug({line:E},"Processing reason line"),E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Zi=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}name="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var ea=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function tg(r){let e=[];for(let n=0;n{f.type==="text"?l.push({type:"text",text:f.text||""}):f.type==="image_url"&&l.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url}})}),!(!a&&l.length===0&&!o.tool_calls&&!o.content)&&(a&&u&&l.length===0&&o.tool_calls&&l.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:l}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:r.max_tokens||1e3,stream:r.stream||!1,...r.temperature&&{temperature:r.temperature}};return r.tools&&r.tools.length>0&&(t.tools=r.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),r.tool_choice&&(r.tool_choice==="auto"||r.tool_choice==="none"?t.tool_choice=r.tool_choice:typeof r.tool_choice=="string"&&(t.tool_choice={type:"tool",name:r.tool_choice})),t}function rg(r){let e=r,n={messages:e.messages.map(o=>{let a=o.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:o.role,content:a}}),model:r.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function ng(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let a={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let _={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_delta"){let _={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_stop")f.enqueue(o.encode(`data: [DONE] + +`));else{let _={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}async function Zw(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>zr(al(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var ta=class{name="vertex-claude";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await Zw();return{body:tg(e),config:{url:new URL(`/v1/projects/${n}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return rg(e)}async transformResponseOut(e){return ng(e,this.name,this.logger)}};function sg(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:typeof e=="object"&&e!==null&&"type"in e&&e.type==="text"&&"text"in e&&typeof e.text=="string"?e.text:"").join(""):""}var ra=class{name="cerebras";async transformRequestIn(e,t){let n=JSON.parse(JSON.stringify(e));if(!n.model&&t.models&&t.models.length>0&&(n.model=t.models[0]),n.system!==void 0){let o=sg(n.system);n.messages||(n.messages=[]),n.messages.unshift({role:"system",content:o}),delete n.system}return n.messages&&Array.isArray(n.messages)&&(n.messages=n.messages.map(o=>{let a={...o};return a.content!==void 0&&(a.content=sg(a.content)),a})),{body:n,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var na=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var og={AnthropicTransformer:bo,GeminiTransformer:Do,VertexGeminiTransformer:Hi,VertexClaudeTransformer:ta,DeepseekTransformer:Gi,TooluseTransformer:Wi,OpenrouterTransformer:zi,MaxTokenTransformer:Ji,GroqTransformer:Vi,CleancacheTransformer:Ki,EnhanceToolTransformer:Xi,ReasoningTransformer:Qi,SamplingTransformer:Zi,MaxCompletionTokens:ea,CerebrasTransformer:ra,StreamOptionsTransformer:na};var sa=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint&&e.push({name:n,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint||e.push({name:n,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=X(X.resolve(e.path));if(t){let n=new t(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path}) +error: ${t.message} +stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message} +Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(og).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}};function rA(r){let e=eA({bodyLimit:52428800,logger:r});return e.setErrorHandler(qf),e.register(tA),e}var Cl=class{app;configService;llmService;providerService;transformerService;constructor(e={}){this.app=rA(e.logger??!0),this.configService=new mo(e),this.transformerService=new sa(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new yo(this.configService,this.transformerService,this.app.log),this.llmService=new go(this.providerService)})}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,a)=>{n.url.startsWith("/v1/messages")&&n.body&&(n.log.info({body:n.body},"request body"),n.body.stream,n.body.stream||(n.body.stream=!1)),a()}),this.app.addHook("preHandler",async(n,o)=>{if(!(n.url.startsWith("/api")||n.method!=="POST"))try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[u,l]=a.model.split(",");a.model=l,n.provider=u;return}catch(a){return n.log.error("Error in modelProviderMiddleware:",a),o.code(500).send({error:"Internal server error"})}}),this.app.register(Uf);let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let t=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},QT=Cl;export{QT as default}; +/*! Bundled license information: + +web-streams-polyfill/dist/ponyfill.es2018.js: + (** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + *) + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +gtoken/build/cjs/src/index.cjs: + (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *) +*/ +//# sourceMappingURL=server.mjs.map diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6ffe5fa61dc38990b88fbe0ee937abcf43368dfe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/unicode.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/util.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/parse.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/stringify.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/index.js", "../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/package.json", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/util.cts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/common.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/retry.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/interceptor.ts", "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/common.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/browser.js", "../../node_modules/.pnpm/has-flag@3.0.0/node_modules/has-flag/index.js", "../../node_modules/.pnpm/supports-color@5.5.0/node_modules/supports-color/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/node.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/index.js", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/helpers.ts", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/index.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/index.ts", "../../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/src/index.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/utils.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/webidl.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/simple-queue.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/internal-methods.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/generic-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isfinite.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/math-trunc.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/basic.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/target/es2018/stub/async-iterator-prototype.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/async-iterator.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isnan.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/ecmascript.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queue-with-sizes.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/array-buffer-view.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byte-stream-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/reader-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byob-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-sink.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abort-signal.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/globals.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/dom-exception.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/pipe.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/tee.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/readable-stream-like.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/from.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-source.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/iterator-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/pipe-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-writable-pair.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy-init.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/byte-length-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/count-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/transformer.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/transform-stream.ts", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js", "../../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js", "../../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/gaxios.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/index.ts", "../../node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/gcp-residency.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/colours.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/logging-utils.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/index.ts", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/index.ts", "../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/shared.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/browser/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/node/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/crypto.js", "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/util.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/package.json", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/shared.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/authclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/loginticket.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/computeclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/idtokenclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/envDetect.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/data-stream.js", "../../node_modules/.pnpm/buffer-equal-constant-time@1.0.1/node_modules/buffer-equal-constant-time/index.js", "../../node_modules/.pnpm/jwa@2.0.1/node_modules/jwa/index.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/tostring.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/sign-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/verify-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/index.js", "../../node_modules/.pnpm/gtoken@8.0.0/node_modules/gtoken/build/cjs/src/index.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtaccess.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/refreshclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/impersonated.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2common.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/stscredentials.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/baseexternalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/identitypoolclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/executable-response.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/googleauth.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/iam.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/downscopedclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/passthrough.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/index.js", "../../src/server.ts", "../../src/services/config.ts", "../../src/api/middleware.ts", "../../src/utils/request.ts", "../../package.json", "../../src/api/routes.ts", "../../src/services/llm.ts", "../../src/services/provider.ts", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/stringify.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/rng.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/native.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/v4.js", "../../src/utils/thinking.ts", "../../src/transformer/anthropic.transformer.ts", "../../src/utils/gemini.util.ts", "../../src/transformer/gemini.transformer.ts", "../../src/transformer/vertex-gemini.transformer.ts", "../../src/transformer/deepseek.transformer.ts", "../../src/transformer/tooluse.transformer.ts", "../../src/transformer/openrouter.transformer.ts", "../../src/transformer/maxtoken.transformer.ts", "../../src/transformer/groq.transformer.ts", "../../src/transformer/cleancache.transformer.ts", "../../src/utils/toolArgumentsParser.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/JSONRepairError.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/stringUtils.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/regular/jsonrepair.ts", "../../src/transformer/enhancetool.transformer.ts", "../../src/transformer/reasoning.transformer.ts", "../../src/transformer/sampling.transformer.ts", "../../src/transformer/maxcompletiontokens.transformer.ts", "../../src/utils/vertex-claude.util.ts", "../../src/transformer/vertex-claude.transformer.ts", "../../src/transformer/cerebras.transformer.ts", "../../src/transformer/streamoptions.transformer.ts", "../../src/transformer/index.ts", "../../src/services/transformer.ts"], + "sourcesContent": ["// This is a generated file. Do not edit.\nmodule.exports.Space_Separator = /[\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/\nmodule.exports.ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\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0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\u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[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/\nmodule.exports.ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0AF9-\\u0AFF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u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C6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\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\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9\\uDF00-\\uDF19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uD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\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/\n", "const unicode = require('../lib/unicode')\n\nmodule.exports = {\n isSpaceSeparator (c) {\n return typeof c === 'string' && unicode.Space_Separator.test(c)\n },\n\n isIdStartChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c === '$') || (c === '_') ||\n unicode.ID_Start.test(c)\n )\n },\n\n isIdContinueChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c >= '0' && c <= '9') ||\n (c === '$') || (c === '_') ||\n (c === '\\u200C') || (c === '\\u200D') ||\n unicode.ID_Continue.test(c)\n )\n },\n\n isDigit (c) {\n return typeof c === 'string' && /[0-9]/.test(c)\n },\n\n isHexDigit (c) {\n return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)\n },\n}\n", "const util = require('./util')\n\nlet source\nlet parseState\nlet stack\nlet pos\nlet line\nlet column\nlet token\nlet key\nlet root\n\nmodule.exports = function parse (text, reviver) {\n source = String(text)\n parseState = 'start'\n stack = []\n pos = 0\n line = 1\n column = 0\n token = undefined\n key = undefined\n root = undefined\n\n do {\n token = lex()\n\n // This code is unreachable.\n // if (!parseStates[parseState]) {\n // throw invalidParseState()\n // }\n\n parseStates[parseState]()\n } while (token.type !== 'eof')\n\n if (typeof reviver === 'function') {\n return internalize({'': root}, '', reviver)\n }\n\n return root\n}\n\nfunction internalize (holder, name, reviver) {\n const value = holder[name]\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const key = String(i)\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n } else {\n for (const key in value) {\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n }\n }\n\n return reviver.call(holder, name, value)\n}\n\nlet lexState\nlet buffer\nlet doubleQuote\nlet sign\nlet c\n\nfunction lex () {\n lexState = 'default'\n buffer = ''\n doubleQuote = false\n sign = 1\n\n for (;;) {\n c = peek()\n\n // This code is unreachable.\n // if (!lexStates[lexState]) {\n // throw invalidLexState(lexState)\n // }\n\n const token = lexStates[lexState]()\n if (token) {\n return token\n }\n }\n}\n\nfunction peek () {\n if (source[pos]) {\n return String.fromCodePoint(source.codePointAt(pos))\n }\n}\n\nfunction read () {\n const c = peek()\n\n if (c === '\\n') {\n line++\n column = 0\n } else if (c) {\n column += c.length\n } else {\n column++\n }\n\n if (c) {\n pos += c.length\n }\n\n return c\n}\n\nconst lexStates = {\n default () {\n switch (c) {\n case '\\t':\n case '\\v':\n case '\\f':\n case ' ':\n case '\\u00A0':\n case '\\uFEFF':\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n return\n\n case '/':\n read()\n lexState = 'comment'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n if (util.isSpaceSeparator(c)) {\n read()\n return\n }\n\n // This code is unreachable.\n // if (!lexStates[parseState]) {\n // throw invalidLexState(parseState)\n // }\n\n return lexStates[parseState]()\n },\n\n comment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineComment'\n return\n\n case '/':\n read()\n lexState = 'singleLineComment'\n return\n }\n\n throw invalidChar(read())\n },\n\n multiLineComment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineCommentAsterisk'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n },\n\n multiLineCommentAsterisk () {\n switch (c) {\n case '*':\n read()\n return\n\n case '/':\n read()\n lexState = 'default'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n lexState = 'multiLineComment'\n },\n\n singleLineComment () {\n switch (c) {\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n lexState = 'default'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n read()\n },\n\n value () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n case 'n':\n read()\n literal('ull')\n return newToken('null', null)\n\n case 't':\n read()\n literal('rue')\n return newToken('boolean', true)\n\n case 'f':\n read()\n literal('alse')\n return newToken('boolean', false)\n\n case '-':\n case '+':\n if (read() === '-') {\n sign = -1\n }\n\n lexState = 'sign'\n return\n\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n buffer = ''\n lexState = 'string'\n return\n }\n\n throw invalidChar(read())\n },\n\n identifierNameStartEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n break\n\n default:\n if (!util.isIdStartChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n identifierName () {\n switch (c) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n buffer += read()\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameEscape'\n return\n }\n\n if (util.isIdContinueChar(c)) {\n buffer += read()\n return\n }\n\n return newToken('identifier', buffer)\n },\n\n identifierNameEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n break\n\n default:\n if (!util.isIdContinueChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n sign () {\n switch (c) {\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', sign * Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n }\n\n throw invalidChar(read())\n },\n\n zero () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n\n case 'x':\n case 'X':\n buffer += read()\n lexState = 'hexadecimal'\n return\n }\n\n return newToken('numeric', sign * 0)\n },\n\n decimalInteger () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalPointLeading () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalPoint () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalFraction () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalExponent () {\n switch (c) {\n case '+':\n case '-':\n buffer += read()\n lexState = 'decimalExponentSign'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentSign () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentInteger () {\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n hexadecimal () {\n if (util.isHexDigit(c)) {\n buffer += read()\n lexState = 'hexadecimalInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n hexadecimalInteger () {\n if (util.isHexDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n string () {\n switch (c) {\n case '\\\\':\n read()\n buffer += escape()\n return\n\n case '\"':\n if (doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case \"'\":\n if (!doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case '\\n':\n case '\\r':\n throw invalidChar(read())\n\n case '\\u2028':\n case '\\u2029':\n separatorChar(c)\n break\n\n case undefined:\n throw invalidChar(read())\n }\n\n buffer += read()\n },\n\n start () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n // This code is unreachable since the default lexState handles eof.\n // case undefined:\n // return newToken('eof')\n }\n\n lexState = 'value'\n },\n\n beforePropertyName () {\n switch (c) {\n case '$':\n case '_':\n buffer = read()\n lexState = 'identifierName'\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameStartEscape'\n return\n\n case '}':\n return newToken('punctuator', read())\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n lexState = 'string'\n return\n }\n\n if (util.isIdStartChar(c)) {\n buffer += read()\n lexState = 'identifierName'\n return\n }\n\n throw invalidChar(read())\n },\n\n afterPropertyName () {\n if (c === ':') {\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforePropertyValue () {\n lexState = 'value'\n },\n\n afterPropertyValue () {\n switch (c) {\n case ',':\n case '}':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforeArrayValue () {\n if (c === ']') {\n return newToken('punctuator', read())\n }\n\n lexState = 'value'\n },\n\n afterArrayValue () {\n switch (c) {\n case ',':\n case ']':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n end () {\n // This code is unreachable since it's handled by the default lexState.\n // if (c === undefined) {\n // read()\n // return newToken('eof')\n // }\n\n throw invalidChar(read())\n },\n}\n\nfunction newToken (type, value) {\n return {\n type,\n value,\n line,\n column,\n }\n}\n\nfunction literal (s) {\n for (const c of s) {\n const p = peek()\n\n if (p !== c) {\n throw invalidChar(read())\n }\n\n read()\n }\n}\n\nfunction escape () {\n const c = peek()\n switch (c) {\n case 'b':\n read()\n return '\\b'\n\n case 'f':\n read()\n return '\\f'\n\n case 'n':\n read()\n return '\\n'\n\n case 'r':\n read()\n return '\\r'\n\n case 't':\n read()\n return '\\t'\n\n case 'v':\n read()\n return '\\v'\n\n case '0':\n read()\n if (util.isDigit(peek())) {\n throw invalidChar(read())\n }\n\n return '\\0'\n\n case 'x':\n read()\n return hexEscape()\n\n case 'u':\n read()\n return unicodeEscape()\n\n case '\\n':\n case '\\u2028':\n case '\\u2029':\n read()\n return ''\n\n case '\\r':\n read()\n if (peek() === '\\n') {\n read()\n }\n\n return ''\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n throw invalidChar(read())\n\n case undefined:\n throw invalidChar(read())\n }\n\n return read()\n}\n\nfunction hexEscape () {\n let buffer = ''\n let c = peek()\n\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nfunction unicodeEscape () {\n let buffer = ''\n let count = 4\n\n while (count-- > 0) {\n const c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n }\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nconst parseStates = {\n start () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforePropertyName () {\n switch (token.type) {\n case 'identifier':\n case 'string':\n key = token.value\n parseState = 'afterPropertyName'\n return\n\n case 'punctuator':\n // This code is unreachable since it's handled by the lexState.\n // if (token.value !== '}') {\n // throw invalidToken()\n // }\n\n pop()\n return\n\n case 'eof':\n throw invalidEOF()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterPropertyName () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator' || token.value !== ':') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n parseState = 'beforePropertyValue'\n },\n\n beforePropertyValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforeArrayValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n if (token.type === 'punctuator' && token.value === ']') {\n pop()\n return\n }\n\n push()\n },\n\n afterPropertyValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforePropertyName'\n return\n\n case '}':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterArrayValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforeArrayValue'\n return\n\n case ']':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n end () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'eof') {\n // throw invalidToken()\n // }\n },\n}\n\nfunction push () {\n let value\n\n switch (token.type) {\n case 'punctuator':\n switch (token.value) {\n case '{':\n value = {}\n break\n\n case '[':\n value = []\n break\n }\n\n break\n\n case 'null':\n case 'boolean':\n case 'numeric':\n case 'string':\n value = token.value\n break\n\n // This code is unreachable.\n // default:\n // throw invalidToken()\n }\n\n if (root === undefined) {\n root = value\n } else {\n const parent = stack[stack.length - 1]\n if (Array.isArray(parent)) {\n parent.push(value)\n } else {\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n if (value !== null && typeof value === 'object') {\n stack.push(value)\n\n if (Array.isArray(value)) {\n parseState = 'beforeArrayValue'\n } else {\n parseState = 'beforePropertyName'\n }\n } else {\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n }\n}\n\nfunction pop () {\n stack.pop()\n\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n}\n\n// This code is unreachable.\n// function invalidParseState () {\n// return new Error(`JSON5: invalid parse state '${parseState}'`)\n// }\n\n// This code is unreachable.\n// function invalidLexState (state) {\n// return new Error(`JSON5: invalid lex state '${state}'`)\n// }\n\nfunction invalidChar (c) {\n if (c === undefined) {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n }\n\n return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n}\n\nfunction invalidEOF () {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n}\n\n// This code is unreachable.\n// function invalidToken () {\n// if (token.type === 'eof') {\n// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n// }\n\n// const c = String.fromCodePoint(token.value.codePointAt(0))\n// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n// }\n\nfunction invalidIdentifier () {\n column -= 5\n return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)\n}\n\nfunction separatorChar (c) {\n console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`)\n}\n\nfunction formatChar (c) {\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n if (replacements[c]) {\n return replacements[c]\n }\n\n if (c < ' ') {\n const hexString = c.charCodeAt(0).toString(16)\n return '\\\\x' + ('00' + hexString).substring(hexString.length)\n }\n\n return c\n}\n\nfunction syntaxError (message) {\n const err = new SyntaxError(message)\n err.lineNumber = line\n err.columnNumber = column\n return err\n}\n", "const util = require('./util')\n\nmodule.exports = function stringify (value, replacer, space) {\n const stack = []\n let indent = ''\n let propertyList\n let replacerFunc\n let gap = ''\n let quote\n\n if (\n replacer != null &&\n typeof replacer === 'object' &&\n !Array.isArray(replacer)\n ) {\n space = replacer.space\n quote = replacer.quote\n replacer = replacer.replacer\n }\n\n if (typeof replacer === 'function') {\n replacerFunc = replacer\n } else if (Array.isArray(replacer)) {\n propertyList = []\n for (const v of replacer) {\n let item\n\n if (typeof v === 'string') {\n item = v\n } else if (\n typeof v === 'number' ||\n v instanceof String ||\n v instanceof Number\n ) {\n item = String(v)\n }\n\n if (item !== undefined && propertyList.indexOf(item) < 0) {\n propertyList.push(item)\n }\n }\n }\n\n if (space instanceof Number) {\n space = Number(space)\n } else if (space instanceof String) {\n space = String(space)\n }\n\n if (typeof space === 'number') {\n if (space > 0) {\n space = Math.min(10, Math.floor(space))\n gap = ' '.substr(0, space)\n }\n } else if (typeof space === 'string') {\n gap = space.substr(0, 10)\n }\n\n return serializeProperty('', {'': value})\n\n function serializeProperty (key, holder) {\n let value = holder[key]\n if (value != null) {\n if (typeof value.toJSON5 === 'function') {\n value = value.toJSON5(key)\n } else if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n }\n\n if (replacerFunc) {\n value = replacerFunc.call(holder, key, value)\n }\n\n if (value instanceof Number) {\n value = Number(value)\n } else if (value instanceof String) {\n value = String(value)\n } else if (value instanceof Boolean) {\n value = value.valueOf()\n }\n\n switch (value) {\n case null: return 'null'\n case true: return 'true'\n case false: return 'false'\n }\n\n if (typeof value === 'string') {\n return quoteString(value, false)\n }\n\n if (typeof value === 'number') {\n return String(value)\n }\n\n if (typeof value === 'object') {\n return Array.isArray(value) ? serializeArray(value) : serializeObject(value)\n }\n\n return undefined\n }\n\n function quoteString (value) {\n const quotes = {\n \"'\": 0.1,\n '\"': 0.2,\n }\n\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n let product = ''\n\n for (let i = 0; i < value.length; i++) {\n const c = value[i]\n switch (c) {\n case \"'\":\n case '\"':\n quotes[c]++\n product += c\n continue\n\n case '\\0':\n if (util.isDigit(value[i + 1])) {\n product += '\\\\x00'\n continue\n }\n }\n\n if (replacements[c]) {\n product += replacements[c]\n continue\n }\n\n if (c < ' ') {\n let hexString = c.charCodeAt(0).toString(16)\n product += '\\\\x' + ('00' + hexString).substring(hexString.length)\n continue\n }\n\n product += c\n }\n\n const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b)\n\n product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar])\n\n return quoteChar + product + quoteChar\n }\n\n function serializeObject (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let keys = propertyList || Object.keys(value)\n let partial = []\n for (const key of keys) {\n const propertyString = serializeProperty(key, value)\n if (propertyString !== undefined) {\n let member = serializeKey(key) + ':'\n if (gap !== '') {\n member += ' '\n }\n member += propertyString\n partial.push(member)\n }\n }\n\n let final\n if (partial.length === 0) {\n final = '{}'\n } else {\n let properties\n if (gap === '') {\n properties = partial.join(',')\n final = '{' + properties + '}'\n } else {\n let separator = ',\\n' + indent\n properties = partial.join(separator)\n final = '{\\n' + indent + properties + ',\\n' + stepback + '}'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n\n function serializeKey (key) {\n if (key.length === 0) {\n return quoteString(key, true)\n }\n\n const firstChar = String.fromCodePoint(key.codePointAt(0))\n if (!util.isIdStartChar(firstChar)) {\n return quoteString(key, true)\n }\n\n for (let i = firstChar.length; i < key.length; i++) {\n if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {\n return quoteString(key, true)\n }\n }\n\n return key\n }\n\n function serializeArray (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let partial = []\n for (let i = 0; i < value.length; i++) {\n const propertyString = serializeProperty(String(i), value)\n partial.push((propertyString !== undefined) ? propertyString : 'null')\n }\n\n let final\n if (partial.length === 0) {\n final = '[]'\n } else {\n if (gap === '') {\n let properties = partial.join(',')\n final = '[' + properties + ']'\n } else {\n let separator = ',\\n' + indent\n let properties = partial.join(separator)\n final = '[\\n' + indent + properties + ',\\n' + stepback + ']'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n}\n", "const parse = require('./parse')\nconst stringify = require('./stringify')\n\nconst JSON5 = {\n parse,\n stringify,\n}\n\nmodule.exports = JSON5\n", "'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n", "{\n \"name\": \"gaxios\",\n \"version\": \"7.1.1\",\n \"description\": \"A simple common HTTP client specifically for Google APIs and services.\",\n \"main\": \"build/cjs/src/index.js\",\n \"types\": \"build/cjs/src/index.d.ts\",\n \"files\": [\n \"build/\"\n ],\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./build/esm/src/index.d.ts\",\n \"default\": \"./build/esm/src/index.js\"\n },\n \"require\": {\n \"types\": \"./build/cjs/src/index.d.ts\",\n \"default\": \"./build/cjs/src/index.js\"\n }\n }\n },\n \"scripts\": {\n \"lint\": \"gts check --no-inline-config\",\n \"test\": \"c8 mocha build/esm/test\",\n \"presystem-test\": \"npm run compile\",\n \"system-test\": \"mocha build/esm/system-test --timeout 80000\",\n \"compile\": \"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs\",\n \"fix\": \"gts fix\",\n \"prepare\": \"npm run compile\",\n \"pretest\": \"npm run compile\",\n \"webpack\": \"webpack\",\n \"prebrowser-test\": \"npm run compile\",\n \"browser-test\": \"node build/browser-test/browser-test-runner.js\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"prelint\": \"cd samples; npm link ../; npm install\",\n \"clean\": \"gts clean\"\n },\n \"repository\": \"googleapis/gaxios\",\n \"keywords\": [\n \"google\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"author\": \"Google, LLC\",\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"@babel/plugin-proposal-private-methods\": \"^7.18.6\",\n \"@types/cors\": \"^2.8.6\",\n \"@types/express\": \"^5.0.0\",\n \"@types/extend\": \"^3.0.1\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/multiparty\": \"4.2.1\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"@types/tmp\": \"0.2.6\",\n \"assert\": \"^2.0.0\",\n \"browserify\": \"^17.0.0\",\n \"c8\": \"^10.0.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^5.0.0\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-remap-coverage\": \"^0.1.5\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"multiparty\": \"^4.2.1\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.0-beta.13\",\n \"null-loader\": \"^4.0.0\",\n \"pack-n-play\": \"^3.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^20.0.0\",\n \"stream-browserify\": \"^3.0.0\",\n \"tmp\": \"0.2.3\",\n \"ts-loader\": \"^9.5.2\",\n \"typescript\": \"^5.8.3\",\n \"webpack\": \"^5.35.0\",\n \"webpack-cli\": \"^6.0.1\"\n },\n \"dependencies\": {\n \"extend\": \"^3.0.2\",\n \"https-proxy-agent\": \"^7.0.1\",\n \"node-fetch\": \"^3.3.2\"\n }\n}\n", null, null, null, null, "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n", "'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", null, null, null, null, "export interface MimeBuffer extends Buffer {\n\ttype: string;\n\ttypeFull: string;\n\tcharset: string;\n}\n\n/**\n * Returns a `Buffer` instance from the given data URI `uri`.\n *\n * @param {String} uri Data URI to turn into a Buffer instance\n * @returns {Buffer} Buffer instance from Data URI\n * @api public\n */\nexport function dataUriToBuffer(uri: string): MimeBuffer {\n\tif (!/^data:/i.test(uri)) {\n\t\tthrow new TypeError(\n\t\t\t'`uri` does not appear to be a Data URI (must begin with \"data:\")'\n\t\t);\n\t}\n\n\t// strip newlines\n\turi = uri.replace(/\\r?\\n/g, '');\n\n\t// split the URI up into the \"metadata\" and the \"data\" portions\n\tconst firstComma = uri.indexOf(',');\n\tif (firstComma === -1 || firstComma <= 4) {\n\t\tthrow new TypeError('malformed data: URI');\n\t}\n\n\t// remove the \"data:\" scheme and parse the metadata\n\tconst meta = uri.substring(5, firstComma).split(';');\n\n\tlet charset = '';\n\tlet base64 = false;\n\tconst type = meta[0] || 'text/plain';\n\tlet typeFull = type;\n\tfor (let i = 1; i < meta.length; i++) {\n\t\tif (meta[i] === 'base64') {\n\t\t\tbase64 = true;\n\t\t} else if(meta[i]) {\n\t\t\ttypeFull += `;${ meta[i]}`;\n\t\t\tif (meta[i].indexOf('charset=') === 0) {\n\t\t\t\tcharset = meta[i].substring(8);\n\t\t\t}\n\t\t}\n\t}\n\t// defaults to US-ASCII only if type is not provided\n\tif (!meta[0] && !charset.length) {\n\t\ttypeFull += ';charset=US-ASCII';\n\t\tcharset = 'US-ASCII';\n\t}\n\n\t// get the encoded data portion and decode URI-encoded chars\n\tconst encoding = base64 ? 'base64' : 'ascii';\n\tconst data = unescape(uri.substring(firstComma + 1));\n\tconst buffer = Buffer.from(data, encoding) as MimeBuffer;\n\n\t// set `.type` and `.typeFull` properties to MIME type\n\tbuffer.type = type;\n\tbuffer.typeFull = typeFull;\n\n\t// set the `.charset` property\n\tbuffer.charset = charset;\n\n\treturn buffer;\n}\n\nexport default dataUriToBuffer;\n", "export function noop(): undefined {\n return undefined;\n}\n", "import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n", "import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n", "import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n", "export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n", "import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n", "import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n", "import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n", "/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n", "/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n", "import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n", "import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n", "export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n", "import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n", "import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n", "/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n", "/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n", "/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n", "import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n", "import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n", "import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n", "import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n", "import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n", "import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n", "import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n", "import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n", "import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n", "import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n", "import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n", "/* c8 ignore start */\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\nif (!globalThis.ReadableStream) {\n // `node:stream/web` got introduced in v16.5.0 as experimental\n // and it's preferred over the polyfilled version. So we also\n // suppress the warning that gets emitted by NodeJS for using it.\n try {\n const process = require('node:process')\n const { emitWarning } = process\n try {\n process.emitWarning = () => {}\n Object.assign(globalThis, require('node:stream/web'))\n process.emitWarning = emitWarning\n } catch (error) {\n process.emitWarning = emitWarning\n throw error\n }\n } catch (error) {\n // fallback to polyfill implementation\n Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js'))\n }\n}\n\ntry {\n // Don't use node: prefix for this, require+node: is not supported until node v14.14\n // Only `import()` can use prefix in 12.20 and later\n const { Blob } = require('buffer')\n if (Blob && !Blob.prototype.stream) {\n Blob.prototype.stream = function name (params) {\n let position = 0\n const blob = this\n\n return new ReadableStream({\n type: 'bytes',\n async pull (ctrl) {\n const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n ctrl.enqueue(new Uint8Array(buffer))\n\n if (position === blob.size) {\n ctrl.close()\n }\n }\n })\n }\n }\n} catch (error) {}\n/* c8 ignore end */\n", "/*! fetch-blob. MIT License. Jimmy W\u00E4rting */\n\n// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)\n// Node has recently added whatwg stream into core\n\nimport './streams.cjs'\n\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\n/** @param {(Blob | Uint8Array)[]} parts */\nasync function * toIterator (parts, clone = true) {\n for (const part of parts) {\n if ('stream' in part) {\n yield * (/** @type {AsyncIterableIterator} */ (part.stream()))\n } else if (ArrayBuffer.isView(part)) {\n if (clone) {\n let position = part.byteOffset\n const end = part.byteOffset + part.byteLength\n while (position !== end) {\n const size = Math.min(end - position, POOL_SIZE)\n const chunk = part.buffer.slice(position, position + size)\n position += chunk.byteLength\n yield new Uint8Array(chunk)\n }\n } else {\n yield part\n }\n /* c8 ignore next 10 */\n } else {\n // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)\n let position = 0, b = (/** @type {Blob} */ (part))\n while (position !== b.size) {\n const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n yield new Uint8Array(buffer)\n }\n }\n }\n}\n\nconst _Blob = class Blob {\n /** @type {Array.<(Blob|Uint8Array)>} */\n #parts = []\n #type = ''\n #size = 0\n #endings = 'transparent'\n\n /**\n * The Blob() constructor returns a new Blob object. The content\n * of the blob consists of the concatenation of the values given\n * in the parameter array.\n *\n * @param {*} blobParts\n * @param {{ type?: string, endings?: string }} [options]\n */\n constructor (blobParts = [], options = {}) {\n if (typeof blobParts !== 'object' || blobParts === null) {\n throw new TypeError('Failed to construct \\'Blob\\': The provided value cannot be converted to a sequence.')\n }\n\n if (typeof blobParts[Symbol.iterator] !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': The object must have a callable @@iterator property.')\n }\n\n if (typeof options !== 'object' && typeof options !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': parameter 2 cannot convert to dictionary.')\n }\n\n if (options === null) options = {}\n\n const encoder = new TextEncoder()\n for (const element of blobParts) {\n let part\n if (ArrayBuffer.isView(element)) {\n part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength))\n } else if (element instanceof ArrayBuffer) {\n part = new Uint8Array(element.slice(0))\n } else if (element instanceof Blob) {\n part = element\n } else {\n part = encoder.encode(`${element}`)\n }\n\n this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size\n this.#parts.push(part)\n }\n\n this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}`\n const type = options.type === undefined ? '' : String(options.type)\n this.#type = /^[\\x20-\\x7E]*$/.test(type) ? type : ''\n }\n\n /**\n * The Blob interface's size property returns the\n * size of the Blob in bytes.\n */\n get size () {\n return this.#size\n }\n\n /**\n * The type property of a Blob object returns the MIME type of the file.\n */\n get type () {\n return this.#type\n }\n\n /**\n * The text() method in the Blob interface returns a Promise\n * that resolves with a string containing the contents of\n * the blob, interpreted as UTF-8.\n *\n * @return {Promise}\n */\n async text () {\n // More optimized than using this.arrayBuffer()\n // that requires twice as much ram\n const decoder = new TextDecoder()\n let str = ''\n for await (const part of toIterator(this.#parts, false)) {\n str += decoder.decode(part, { stream: true })\n }\n // Remaining\n str += decoder.decode()\n return str\n }\n\n /**\n * The arrayBuffer() method in the Blob interface returns a\n * Promise that resolves with the contents of the blob as\n * binary data contained in an ArrayBuffer.\n *\n * @return {Promise}\n */\n async arrayBuffer () {\n // Easier way... Just a unnecessary overhead\n // const view = new Uint8Array(this.size);\n // await this.stream().getReader({mode: 'byob'}).read(view);\n // return view.buffer;\n\n const data = new Uint8Array(this.size)\n let offset = 0\n for await (const chunk of toIterator(this.#parts, false)) {\n data.set(chunk, offset)\n offset += chunk.length\n }\n\n return data.buffer\n }\n\n stream () {\n const it = toIterator(this.#parts, true)\n\n return new globalThis.ReadableStream({\n // @ts-ignore\n type: 'bytes',\n async pull (ctrl) {\n const chunk = await it.next()\n chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value)\n },\n\n async cancel () {\n await it.return()\n }\n })\n }\n\n /**\n * The Blob interface's slice() method creates and returns a\n * new Blob object which contains data from a subset of the\n * blob on which it's called.\n *\n * @param {number} [start]\n * @param {number} [end]\n * @param {string} [type]\n */\n slice (start = 0, end = this.size, type = '') {\n const { size } = this\n\n let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size)\n let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size)\n\n const span = Math.max(relativeEnd - relativeStart, 0)\n const parts = this.#parts\n const blobParts = []\n let added = 0\n\n for (const part of parts) {\n // don't add the overflow to new blobParts\n if (added >= span) {\n break\n }\n\n const size = ArrayBuffer.isView(part) ? part.byteLength : part.size\n if (relativeStart && size <= relativeStart) {\n // Skip the beginning and change the relative\n // start & end position as we skip the unwanted parts\n relativeStart -= size\n relativeEnd -= size\n } else {\n let chunk\n if (ArrayBuffer.isView(part)) {\n chunk = part.subarray(relativeStart, Math.min(size, relativeEnd))\n added += chunk.byteLength\n } else {\n chunk = part.slice(relativeStart, Math.min(size, relativeEnd))\n added += chunk.size\n }\n relativeEnd -= size\n blobParts.push(chunk)\n relativeStart = 0 // All next sequential parts should start at 0\n }\n }\n\n const blob = new Blob([], { type: String(type).toLowerCase() })\n blob.#size = span\n blob.#parts = blobParts\n\n return blob\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n\n static [Symbol.hasInstance] (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.constructor === 'function' &&\n (\n typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function'\n ) &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n }\n}\n\nObject.defineProperties(_Blob.prototype, {\n size: { enumerable: true },\n type: { enumerable: true },\n slice: { enumerable: true }\n})\n\n/** @type {typeof globalThis.Blob} */\nexport const Blob = _Blob\nexport default Blob\n", "import Blob from './index.js'\n\nconst _File = class File extends Blob {\n #lastModified = 0\n #name = ''\n\n /**\n * @param {*[]} fileBits\n * @param {string} fileName\n * @param {{lastModified?: number, type?: string}} options\n */// @ts-ignore\n constructor (fileBits, fileName, options = {}) {\n if (arguments.length < 2) {\n throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`)\n }\n super(fileBits, options)\n\n if (options === null) options = {}\n\n // Simulate WebIDL type casting for NaN value in lastModified option.\n const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified)\n if (!Number.isNaN(lastModified)) {\n this.#lastModified = lastModified\n }\n\n this.#name = String(fileName)\n }\n\n get name () {\n return this.#name\n }\n\n get lastModified () {\n return this.#lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n\n static [Symbol.hasInstance] (object) {\n return !!object && object instanceof Blob &&\n /^(File)$/.test(object[Symbol.toStringTag])\n }\n}\n\n/** @type {typeof globalThis.File} */// @ts-ignore\nexport const File = _File\nexport default File\n", "/*! formdata-polyfill. MIT License. Jimmy W\u00E4rting */\n\nimport C from 'fetch-blob'\nimport F from 'fetch-blob/file.js'\n\nvar {toStringTag:t,iterator:i,hasInstance:h}=Symbol,\nr=Math.random,\nm='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','),\nf=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']),\ne=(c,f)=>(f?c:c.replace(/\\r?\\n|\\r/g,'\\r\\n')).replace(/\\n/g,'%0A').replace(/\\r/g,'%0D').replace(/\"/g,'%22'),\nx=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')}\nappend(...a){x('append',arguments,2);this.#d.push(f(...a))}\ndelete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)}\nget(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b}\nhas(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)}\nforEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)}\nset(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b}\n*entries(){yield*this.#d}\n*keys(){for(var[a]of this)yield a}\n*values(){for(var[,a]of this)yield a}}\n\n/** @param {FormData} F */\nexport function formDataToBlob (F,B=C){\nvar b=`${r()}${r()}`.replace(/\\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\\r\\nContent-Disposition: form-data; name=\"`\nF.forEach((v,n)=>typeof v=='string'\n?c.push(p+e(n)+`\"\\r\\n\\r\\n${v.replace(/\\r(?!\\n)|(? {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.append === 'function' &&\n\t\ttypeof object.delete === 'function' &&\n\t\ttypeof object.get === 'function' &&\n\t\ttypeof object.getAll === 'function' &&\n\t\ttypeof object.has === 'function' &&\n\t\ttypeof object.set === 'function' &&\n\t\ttypeof object.sort === 'function' &&\n\t\tobject[NAME] === 'URLSearchParams'\n\t);\n};\n\n/**\n * Check if `object` is a W3C `Blob` object (which `File` inherits from)\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isBlob = object => {\n\treturn (\n\t\tobject &&\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.arrayBuffer === 'function' &&\n\t\ttypeof object.type === 'string' &&\n\t\ttypeof object.stream === 'function' &&\n\t\ttypeof object.constructor === 'function' &&\n\t\t/^(Blob|File)$/.test(object[NAME])\n\t);\n};\n\n/**\n * Check if `obj` is an instance of AbortSignal.\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isAbortSignal = object => {\n\treturn (\n\t\ttypeof object === 'object' && (\n\t\t\tobject[NAME] === 'AbortSignal' ||\n\t\t\tobject[NAME] === 'EventTarget'\n\t\t)\n\t);\n};\n\n/**\n * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of\n * the parent domain.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isDomainOrSubdomain = (destination, original) => {\n\tconst orig = new URL(original).hostname;\n\tconst dest = new URL(destination).hostname;\n\n\treturn orig === dest || orig.endsWith(`.${dest}`);\n};\n\n/**\n * isSameProtocol reports whether the two provided URLs use the same protocol.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isSameProtocol = (destination, original) => {\n\tconst orig = new URL(original).protocol;\n\tconst dest = new URL(destination).protocol;\n\n\treturn orig === dest;\n};\n", "/*! node-domexception. MIT License. Jimmy W\u00E4rting */\n\nif (!globalThis.DOMException) {\n try {\n const { MessageChannel } = require('worker_threads'),\n port = new MessageChannel().port1,\n ab = new ArrayBuffer()\n port.postMessage(ab, [ab, ab])\n } catch (err) {\n err.constructor.name === 'DOMException' && (\n globalThis.DOMException = err.constructor\n )\n }\n}\n\nmodule.exports = globalThis.DOMException\n", "import { statSync, createReadStream, promises as fs } from 'node:fs'\nimport { basename } from 'node:path'\nimport DOMException from 'node-domexception'\n\nimport File from './file.js'\nimport Blob from './index.js'\n\nconst { stat } = fs\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst blobFromSync = (path, type) => fromBlob(statSync(path), path, type)\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst fileFromSync = (path, type) => fromFile(statSync(path), path, type)\n\n// @ts-ignore\nconst fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], { type })\n\n// @ts-ignore\nconst fromFile = (stat, path, type = '') => new File([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], basename(path), { type, lastModified: stat.mtimeMs })\n\n/**\n * This is a blob backed up by a file on the disk\n * with minium requirement. Its wrapped around a Blob as a blobPart\n * so you have no direct access to this.\n *\n * @private\n */\nclass BlobDataItem {\n #path\n #start\n\n constructor (options) {\n this.#path = options.path\n this.#start = options.start\n this.size = options.size\n this.lastModified = options.lastModified\n }\n\n /**\n * Slicing arguments is first validated and formatted\n * to not be out of range by Blob.prototype.slice\n */\n slice (start, end) {\n return new BlobDataItem({\n path: this.#path,\n lastModified: this.lastModified,\n size: end - start,\n start: this.#start + start\n })\n }\n\n async * stream () {\n const { mtimeMs } = await stat(this.#path)\n if (mtimeMs > this.lastModified) {\n throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError')\n }\n yield * createReadStream(this.#path, {\n start: this.#start,\n end: this.#start + this.size - 1\n })\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n}\n\nexport default blobFromSync\nexport { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync }\n", "import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/&#(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n", "\n/**\n * Body.js\n *\n * Body interface provides common methods for Request and Response\n */\n\nimport Stream, {PassThrough} from 'node:stream';\nimport {types, deprecate, promisify} from 'node:util';\nimport {Buffer} from 'node:buffer';\n\nimport Blob from 'fetch-blob';\nimport {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';\n\nimport {FetchError} from './errors/fetch-error.js';\nimport {FetchBaseError} from './errors/base.js';\nimport {isBlob, isURLSearchParameters} from './utils/is.js';\n\nconst pipeline = promisify(Stream.pipeline);\nconst INTERNALS = Symbol('Body internals');\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Body {\n\tconstructor(body, {\n\t\tsize = 0\n\t} = {}) {\n\t\tlet boundary = null;\n\n\t\tif (body === null) {\n\t\t\t// Body is undefined or null\n\t\t\tbody = null;\n\t\t} else if (isURLSearchParameters(body)) {\n\t\t\t// Body is a URLSearchParams\n\t\t\tbody = Buffer.from(body.toString());\n\t\t} else if (isBlob(body)) {\n\t\t\t// Body is blob\n\t\t} else if (Buffer.isBuffer(body)) {\n\t\t\t// Body is Buffer\n\t\t} else if (types.isAnyArrayBuffer(body)) {\n\t\t\t// Body is ArrayBuffer\n\t\t\tbody = Buffer.from(body);\n\t\t} else if (ArrayBuffer.isView(body)) {\n\t\t\t// Body is ArrayBufferView\n\t\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t\t} else if (body instanceof Stream) {\n\t\t\t// Body is stream\n\t\t} else if (body instanceof FormData) {\n\t\t\t// Body is FormData\n\t\t\tbody = formDataToBlob(body);\n\t\t\tboundary = body.type.split('=')[1];\n\t\t} else {\n\t\t\t// None of the above\n\t\t\t// coerce to string then buffer\n\t\t\tbody = Buffer.from(String(body));\n\t\t}\n\n\t\tlet stream = body;\n\n\t\tif (Buffer.isBuffer(body)) {\n\t\t\tstream = Stream.Readable.from(body);\n\t\t} else if (isBlob(body)) {\n\t\t\tstream = Stream.Readable.from(body.stream());\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tbody,\n\t\t\tstream,\n\t\t\tboundary,\n\t\t\tdisturbed: false,\n\t\t\terror: null\n\t\t};\n\t\tthis.size = size;\n\n\t\tif (body instanceof Stream) {\n\t\t\tbody.on('error', error_ => {\n\t\t\t\tconst error = error_ instanceof FetchBaseError ?\n\t\t\t\t\terror_ :\n\t\t\t\t\tnew FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);\n\t\t\t\tthis[INTERNALS].error = error;\n\t\t\t});\n\t\t}\n\t}\n\n\tget body() {\n\t\treturn this[INTERNALS].stream;\n\t}\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t}\n\n\t/**\n\t * Decode response as ArrayBuffer\n\t *\n\t * @return Promise\n\t */\n\tasync arrayBuffer() {\n\t\tconst {buffer, byteOffset, byteLength} = await consumeBody(this);\n\t\treturn buffer.slice(byteOffset, byteOffset + byteLength);\n\t}\n\n\tasync formData() {\n\t\tconst ct = this.headers.get('content-type');\n\n\t\tif (ct.startsWith('application/x-www-form-urlencoded')) {\n\t\t\tconst formData = new FormData();\n\t\t\tconst parameters = new URLSearchParams(await this.text());\n\n\t\t\tfor (const [name, value] of parameters) {\n\t\t\t\tformData.append(name, value);\n\t\t\t}\n\n\t\t\treturn formData;\n\t\t}\n\n\t\tconst {toFormData} = await import('./utils/multipart-parser.js');\n\t\treturn toFormData(this.body, ct);\n\t}\n\n\t/**\n\t * Return raw response as Blob\n\t *\n\t * @return Promise\n\t */\n\tasync blob() {\n\t\tconst ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || '';\n\t\tconst buf = await this.arrayBuffer();\n\n\t\treturn new Blob([buf], {\n\t\t\ttype: ct\n\t\t});\n\t}\n\n\t/**\n\t * Decode response as json\n\t *\n\t * @return Promise\n\t */\n\tasync json() {\n\t\tconst text = await this.text();\n\t\treturn JSON.parse(text);\n\t}\n\n\t/**\n\t * Decode response as text\n\t *\n\t * @return Promise\n\t */\n\tasync text() {\n\t\tconst buffer = await consumeBody(this);\n\t\treturn new TextDecoder().decode(buffer);\n\t}\n\n\t/**\n\t * Decode response as buffer (non-spec api)\n\t *\n\t * @return Promise\n\t */\n\tbuffer() {\n\t\treturn consumeBody(this);\n\t}\n}\n\nBody.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \\'response.arrayBuffer()\\' instead of \\'response.buffer()\\'', 'node-fetch#buffer');\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: {enumerable: true},\n\tbodyUsed: {enumerable: true},\n\tarrayBuffer: {enumerable: true},\n\tblob: {enumerable: true},\n\tjson: {enumerable: true},\n\ttext: {enumerable: true},\n\tdata: {get: deprecate(() => {},\n\t\t'data doesn\\'t exist, use json(), text(), arrayBuffer(), or body instead',\n\t\t'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}\n});\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return Promise\n */\nasync function consumeBody(data) {\n\tif (data[INTERNALS].disturbed) {\n\t\tthrow new TypeError(`body used already for: ${data.url}`);\n\t}\n\n\tdata[INTERNALS].disturbed = true;\n\n\tif (data[INTERNALS].error) {\n\t\tthrow data[INTERNALS].error;\n\t}\n\n\tconst {body} = data;\n\n\t// Body is null\n\tif (body === null) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t/* c8 ignore next 3 */\n\tif (!(body instanceof Stream)) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t// Body is stream\n\t// get ready to actually consume the body\n\tconst accum = [];\n\tlet accumBytes = 0;\n\n\ttry {\n\t\tfor await (const chunk of body) {\n\t\t\tif (data.size > 0 && accumBytes + chunk.length > data.size) {\n\t\t\t\tconst error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');\n\t\t\t\tbody.destroy(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t}\n\t} catch (error) {\n\t\tconst error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);\n\t\tthrow error_;\n\t}\n\n\tif (body.readableEnded === true || body._readableState.ended === true) {\n\t\ttry {\n\t\t\tif (accum.every(c => typeof c === 'string')) {\n\t\t\t\treturn Buffer.from(accum.join(''));\n\t\t\t}\n\n\t\t\treturn Buffer.concat(accum, accumBytes);\n\t\t} catch (error) {\n\t\t\tthrow new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);\n\t\t}\n\t} else {\n\t\tthrow new FetchError(`Premature close of server response while trying to fetch ${data.url}`);\n\t}\n}\n\n/**\n * Clone body given Res/Req instance\n *\n * @param Mixed instance Response or Request instance\n * @param String highWaterMark highWaterMark for both PassThrough body streams\n * @return Mixed\n */\nexport const clone = (instance, highWaterMark) => {\n\tlet p1;\n\tlet p2;\n\tlet {body} = instance[INTERNALS];\n\n\t// Don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// Check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) {\n\t\t// Tee instance body\n\t\tp1 = new PassThrough({highWaterMark});\n\t\tp2 = new PassThrough({highWaterMark});\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// Set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].stream = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n};\n\nconst getNonSpecFormDataBoundary = deprecate(\n\tbody => body.getBoundary(),\n\t'form-data doesn\\'t follow the spec and requires special treatment. Use alternative package',\n\t'https://github.com/node-fetch/node-fetch/issues/1167'\n);\n\n/**\n * Performs the operation \"extract a `Content-Type` value from |object|\" as\n * specified in the specification:\n * https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n *\n * This function assumes that instance.body is present.\n *\n * @param {any} body Any options.body input\n * @returns {string | null}\n */\nexport const extractContentType = (body, request) => {\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn null;\n\t}\n\n\t// Body is string\n\tif (typeof body === 'string') {\n\t\treturn 'text/plain;charset=UTF-8';\n\t}\n\n\t// Body is a URLSearchParams\n\tif (isURLSearchParameters(body)) {\n\t\treturn 'application/x-www-form-urlencoded;charset=UTF-8';\n\t}\n\n\t// Body is blob\n\tif (isBlob(body)) {\n\t\treturn body.type || null;\n\t}\n\n\t// Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)\n\tif (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {\n\t\treturn null;\n\t}\n\n\tif (body instanceof FormData) {\n\t\treturn `multipart/form-data; boundary=${request[INTERNALS].boundary}`;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getBoundary === 'function') {\n\t\treturn `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;\n\t}\n\n\t// Body is stream - can't really do much about this\n\tif (body instanceof Stream) {\n\t\treturn null;\n\t}\n\n\t// Body constructor defaults other things to string\n\treturn 'text/plain;charset=UTF-8';\n};\n\n/**\n * The Fetch Standard treats this as if \"total bytes\" is a property on the body.\n * For us, we have to explicitly get it with a function.\n *\n * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes\n *\n * @param {any} obj.body Body object from the Body instance.\n * @returns {number | null}\n */\nexport const getTotalBytes = request => {\n\tconst {body} = request[INTERNALS];\n\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn 0;\n\t}\n\n\t// Body is Blob\n\tif (isBlob(body)) {\n\t\treturn body.size;\n\t}\n\n\t// Body is Buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn body.length;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getLengthSync === 'function') {\n\t\treturn body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;\n\t}\n\n\t// Body is stream\n\treturn null;\n};\n\n/**\n * Write a Body to a Node.js WritableStream (e.g. http.Request) object.\n *\n * @param {Stream.Writable} dest The stream to write to.\n * @param obj.body Body object from the Body instance.\n * @returns {Promise}\n */\nexport const writeToStream = async (dest, {body}) => {\n\tif (body === null) {\n\t\t// Body is null\n\t\tdest.end();\n\t} else {\n\t\t// Body is stream\n\t\tawait pipeline(body, dest);\n\t}\n};\n", "/**\n * Headers.js\n *\n * Headers class offers convenient helpers\n */\n\nimport {types} from 'node:util';\nimport http from 'node:http';\n\n/* c8 ignore next 9 */\nconst validateHeaderName = typeof http.validateHeaderName === 'function' ?\n\thttp.validateHeaderName :\n\tname => {\n\t\tif (!/^[\\^`\\-\\w!#$%&'*+.|~]+$/.test(name)) {\n\t\t\tconst error = new TypeError(`Header name must be a valid HTTP token [${name}]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/* c8 ignore next 9 */\nconst validateHeaderValue = typeof http.validateHeaderValue === 'function' ?\n\thttp.validateHeaderValue :\n\t(name, value) => {\n\t\tif (/[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/.test(value)) {\n\t\t\tconst error = new TypeError(`Invalid character in header content [\"${name}\"]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/**\n * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit\n */\n\n/**\n * This Fetch API interface allows you to perform various actions on HTTP request and response headers.\n * These actions include retrieving, setting, adding to, and removing.\n * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.\n * You can add to this using methods like append() (see Examples.)\n * In all methods of this interface, header names are matched by case-insensitive byte sequence.\n *\n */\nexport default class Headers extends URLSearchParams {\n\t/**\n\t * Headers class\n\t *\n\t * @constructor\n\t * @param {HeadersInit} [init] - Response headers\n\t */\n\tconstructor(init) {\n\t\t// Validate and normalize init object in [name, value(s)][]\n\t\t/** @type {string[][]} */\n\t\tlet result = [];\n\t\tif (init instanceof Headers) {\n\t\t\tconst raw = init.raw();\n\t\t\tfor (const [name, values] of Object.entries(raw)) {\n\t\t\t\tresult.push(...values.map(value => [name, value]));\n\t\t\t}\n\t\t} else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\t\t// No op\n\t\t} else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (method == null) {\n\t\t\t\t// Record\n\t\t\t\tresult.push(...Object.entries(init));\n\t\t\t} else {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// Sequence>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tresult = [...init]\n\t\t\t\t\t.map(pair => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof pair !== 'object' || types.isBoxedPrimitive(pair)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be an iterable object');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t}).map(pair => {\n\t\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Failed to construct \\'Headers\\': The provided value is not of type \\'(sequence> or record)');\n\t\t}\n\n\t\t// Validate and lowercase\n\t\tresult =\n\t\t\tresult.length > 0 ?\n\t\t\t\tresult.map(([name, value]) => {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn [String(name).toLowerCase(), String(value)];\n\t\t\t\t}) :\n\t\t\t\tundefined;\n\n\t\tsuper(result);\n\n\t\t// Returning a Proxy that will lowercase key names, validate parameters and sort keys\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn new Proxy(this, {\n\t\t\tget(target, p, receiver) {\n\t\t\t\tswitch (p) {\n\t\t\t\t\tcase 'append':\n\t\t\t\t\tcase 'set':\n\t\t\t\t\t\treturn (name, value) => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase(),\n\t\t\t\t\t\t\t\tString(value)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'delete':\n\t\t\t\t\tcase 'has':\n\t\t\t\t\tcase 'getAll':\n\t\t\t\t\t\treturn name => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase()\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'keys':\n\t\t\t\t\t\treturn () => {\n\t\t\t\t\t\t\ttarget.sort();\n\t\t\t\t\t\t\treturn new Set(URLSearchParams.prototype.keys.call(target)).keys();\n\t\t\t\t\t\t};\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn Reflect.get(target, p, receiver);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t/* c8 ignore next */\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn this.constructor.name;\n\t}\n\n\ttoString() {\n\t\treturn Object.prototype.toString.call(this);\n\t}\n\n\tget(name) {\n\t\tconst values = this.getAll(name);\n\t\tif (values.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet value = values.join(', ');\n\t\tif (/^content-encoding$/i.test(name)) {\n\t\t\tvalue = value.toLowerCase();\n\t\t}\n\n\t\treturn value;\n\t}\n\n\tforEach(callback, thisArg = undefined) {\n\t\tfor (const name of this.keys()) {\n\t\t\tReflect.apply(callback, thisArg, [this.get(name), name, this]);\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield this.get(name);\n\t\t}\n\t}\n\n\t/**\n\t * @type {() => IterableIterator<[string, string]>}\n\t */\n\t* entries() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield [name, this.get(name)];\n\t\t}\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\n\t/**\n\t * Node-fetch non-spec method\n\t * returning all headers and their values as array\n\t * @returns {Record}\n\t */\n\traw() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tresult[key] = this.getAll(key);\n\t\t\treturn result;\n\t\t}, {});\n\t}\n\n\t/**\n\t * For better console.log(headers) and also to convert Headers into Node.js Request compatible format\n\t */\n\t[Symbol.for('nodejs.util.inspect.custom')]() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tconst values = this.getAll(key);\n\t\t\t// Http.request() only supports string as Host header.\n\t\t\t// This hack makes specifying custom Host header possible.\n\t\t\tif (key === 'host') {\n\t\t\t\tresult[key] = values[0];\n\t\t\t} else {\n\t\t\t\tresult[key] = values.length > 1 ? values : values[0];\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}, {});\n\t}\n}\n\n/**\n * Re-shaping object for Web IDL tests\n * Only need to do it for overridden methods\n */\nObject.defineProperties(\n\tHeaders.prototype,\n\t['get', 'entries', 'forEach', 'values'].reduce((result, property) => {\n\t\tresult[property] = {enumerable: true};\n\t\treturn result;\n\t}, {})\n);\n\n/**\n * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do\n * not conform to HTTP grammar productions.\n * @param {import('http').IncomingMessage['rawHeaders']} headers\n */\nexport function fromRawHeaders(headers = []) {\n\treturn new Headers(\n\t\theaders\n\t\t\t// Split into pairs\n\t\t\t.reduce((result, value, index, array) => {\n\t\t\t\tif (index % 2 === 0) {\n\t\t\t\t\tresult.push(array.slice(index, index + 2));\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}, [])\n\t\t\t.filter(([name, value]) => {\n\t\t\t\ttry {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t})\n\n\t);\n}\n", "const redirectStatus = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Redirect code matching\n *\n * @param {number} code - Status code\n * @return {boolean}\n */\nexport const isRedirect = code => {\n\treturn redirectStatus.has(code);\n};\n", "/**\n * Response.js\n *\n * Response class provides content decoding\n */\n\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType} from './body.js';\nimport {isRedirect} from './utils/is-redirect.js';\n\nconst INTERNALS = Symbol('Response internals');\n\n/**\n * Response class\n *\n * Ref: https://fetch.spec.whatwg.org/#response-class\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Response extends Body {\n\tconstructor(body = null, options = {}) {\n\t\tsuper(body, options);\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition\n\t\tconst status = options.status != null ? options.status : 200;\n\n\t\tconst headers = new Headers(options.headers);\n\n\t\tif (body !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\ttype: 'default',\n\t\t\turl: options.url,\n\t\t\tstatus,\n\t\t\tstatusText: options.statusText || '',\n\t\t\theaders,\n\t\t\tcounter: options.counter,\n\t\t\thighWaterMark: options.highWaterMark\n\t\t};\n\t}\n\n\tget type() {\n\t\treturn this[INTERNALS].type;\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS].status;\n\t}\n\n\t/**\n\t * Convenience property representing if the request ended normally\n\t */\n\tget ok() {\n\t\treturn this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget highWaterMark() {\n\t\treturn this[INTERNALS].highWaterMark;\n\t}\n\n\t/**\n\t * Clone this response\n\t *\n\t * @return Response\n\t */\n\tclone() {\n\t\treturn new Response(clone(this, this.highWaterMark), {\n\t\t\ttype: this.type,\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected,\n\t\t\tsize: this.size,\n\t\t\thighWaterMark: this.highWaterMark\n\t\t});\n\t}\n\n\t/**\n\t * @param {string} url The URL that the new response is to originate from.\n\t * @param {number} status An optional status code for the response (e.g., 302.)\n\t * @returns {Response} A Response object.\n\t */\n\tstatic redirect(url, status = 302) {\n\t\tif (!isRedirect(status)) {\n\t\t\tthrow new RangeError('Failed to execute \"redirect\" on \"response\": Invalid status code');\n\t\t}\n\n\t\treturn new Response(null, {\n\t\t\theaders: {\n\t\t\t\tlocation: new URL(url).toString()\n\t\t\t},\n\t\t\tstatus\n\t\t});\n\t}\n\n\tstatic error() {\n\t\tconst response = new Response(null, {status: 0, statusText: ''});\n\t\tresponse[INTERNALS].type = 'error';\n\t\treturn response;\n\t}\n\n\tstatic json(data = undefined, init = {}) {\n\t\tconst body = JSON.stringify(data);\n\n\t\tif (body === undefined) {\n\t\t\tthrow new TypeError('data is not JSON serializable');\n\t\t}\n\n\t\tconst headers = new Headers(init && init.headers);\n\n\t\tif (!headers.has('content-type')) {\n\t\t\theaders.set('content-type', 'application/json');\n\t\t}\n\n\t\treturn new Response(body, {\n\t\t\t...init,\n\t\t\theaders\n\t\t});\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Response';\n\t}\n}\n\nObject.defineProperties(Response.prototype, {\n\ttype: {enumerable: true},\n\turl: {enumerable: true},\n\tstatus: {enumerable: true},\n\tok: {enumerable: true},\n\tredirected: {enumerable: true},\n\tstatusText: {enumerable: true},\n\theaders: {enumerable: true},\n\tclone: {enumerable: true}\n});\n", "export const getSearch = parsedURL => {\n\tif (parsedURL.search) {\n\t\treturn parsedURL.search;\n\t}\n\n\tconst lastOffset = parsedURL.href.length - 1;\n\tconst hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : '');\n\treturn parsedURL.href[lastOffset - hash.length] === '?' ? '?' : '';\n};\n", "import {isIP} from 'node:net';\n\n/**\n * @external URL\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}\n */\n\n/**\n * @module utils/referrer\n * @private\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy \u00A78.4. Strip url for use as a referrer}\n * @param {string} URL\n * @param {boolean} [originOnly=false]\n */\nexport function stripURLForUseAsAReferrer(url, originOnly = false) {\n\t// 1. If url is null, return no referrer.\n\tif (url == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\treturn 'no-referrer';\n\t}\n\n\turl = new URL(url);\n\n\t// 2. If url's scheme is a local scheme, then return no referrer.\n\tif (/^(about|blob|data):$/.test(url.protocol)) {\n\t\treturn 'no-referrer';\n\t}\n\n\t// 3. Set url's username to the empty string.\n\turl.username = '';\n\n\t// 4. Set url's password to null.\n\t// Note: `null` appears to be a mistake as this actually results in the password being `\"null\"`.\n\turl.password = '';\n\n\t// 5. Set url's fragment to null.\n\t// Note: `null` appears to be a mistake as this actually results in the fragment being `\"#null\"`.\n\turl.hash = '';\n\n\t// 6. If the origin-only flag is true, then:\n\tif (originOnly) {\n\t\t// 6.1. Set url's path to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the path being `\"/null\"`.\n\t\turl.pathname = '';\n\n\t\t// 6.2. Set url's query to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the query being `\"?null\"`.\n\t\turl.search = '';\n\t}\n\n\t// 7. Return url.\n\treturn url;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy}\n */\nexport const ReferrerPolicy = new Set([\n\t'',\n\t'no-referrer',\n\t'no-referrer-when-downgrade',\n\t'same-origin',\n\t'origin',\n\t'strict-origin',\n\t'origin-when-cross-origin',\n\t'strict-origin-when-cross-origin',\n\t'unsafe-url'\n]);\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy}\n */\nexport const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy \u00A73. Referrer Policies}\n * @param {string} referrerPolicy\n * @returns {string} referrerPolicy\n */\nexport function validateReferrerPolicy(referrerPolicy) {\n\tif (!ReferrerPolicy.has(referrerPolicy)) {\n\t\tthrow new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);\n\t}\n\n\treturn referrerPolicy;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy \u00A73.2. Is origin potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isOriginPotentiallyTrustworthy(url) {\n\t// 1. If origin is an opaque origin, return \"Not Trustworthy\".\n\t// Not applicable\n\n\t// 2. Assert: origin is a tuple origin.\n\t// Not for implementations\n\n\t// 3. If origin's scheme is either \"https\" or \"wss\", return \"Potentially Trustworthy\".\n\tif (/^(http|ws)s:$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return \"Potentially Trustworthy\".\n\tconst hostIp = url.host.replace(/(^\\[)|(]$)/g, '');\n\tconst hostIPVersion = isIP(hostIp);\n\n\tif (hostIPVersion === 4 && /^127\\./.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\tif (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\t// 5. If origin's host component is \"localhost\" or falls within \".localhost\", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return \"Potentially Trustworthy\".\n\t// We are returning FALSE here because we cannot ensure conformance to\n\t// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)\n\tif (url.host === 'localhost' || url.host.endsWith('.localhost')) {\n\t\treturn false;\n\t}\n\n\t// 6. If origin's scheme component is file, return \"Potentially Trustworthy\".\n\tif (url.protocol === 'file:') {\n\t\treturn true;\n\t}\n\n\t// 7. If origin's scheme component is one which the user agent considers to be authenticated, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 8. If origin has been configured as a trustworthy origin, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 9. Return \"Not Trustworthy\".\n\treturn false;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy \u00A73.3. Is url potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isUrlPotentiallyTrustworthy(url) {\n\t// 1. If url is \"about:blank\" or \"about:srcdoc\", return \"Potentially Trustworthy\".\n\tif (/^about:(blank|srcdoc)$/.test(url)) {\n\t\treturn true;\n\t}\n\n\t// 2. If url's scheme is \"data\", return \"Potentially Trustworthy\".\n\tif (url.protocol === 'data:') {\n\t\treturn true;\n\t}\n\n\t// Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were\n\t// created. Therefore, blobs created in a trustworthy origin will themselves be potentially\n\t// trustworthy.\n\tif (/^(blob|filesystem):$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 3. Return the result of executing \u00A73.2 Is origin potentially trustworthy? on url's origin.\n\treturn isOriginPotentiallyTrustworthy(url);\n}\n\n/**\n * Modifies the referrerURL to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerURLCallback\n * @param {external:URL} referrerURL\n * @returns {external:URL} modified referrerURL\n */\n\n/**\n * Modifies the referrerOrigin to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerOriginCallback\n * @param {external:URL} referrerOrigin\n * @returns {external:URL} modified referrerOrigin\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}\n * @param {Request} request\n * @param {object} o\n * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback\n * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback\n * @returns {external:URL} Request's referrer\n */\nexport function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) {\n\t// There are 2 notes in the specification about invalid pre-conditions. We return null, here, for\n\t// these cases:\n\t// > Note: If request's referrer is \"no-referrer\", Fetch will not call into this algorithm.\n\t// > Note: If request's referrer policy is the empty string, Fetch will not call into this\n\t// > algorithm.\n\tif (request.referrer === 'no-referrer' || request.referrerPolicy === '') {\n\t\treturn null;\n\t}\n\n\t// 1. Let policy be request's associated referrer policy.\n\tconst policy = request.referrerPolicy;\n\n\t// 2. Let environment be request's client.\n\t// not applicable to node.js\n\n\t// 3. Switch on request's referrer:\n\tif (request.referrer === 'about:client') {\n\t\treturn 'no-referrer';\n\t}\n\n\t// \"a URL\": Let referrerSource be request's referrer.\n\tconst referrerSource = request.referrer;\n\n\t// 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer.\n\tlet referrerURL = stripURLForUseAsAReferrer(referrerSource);\n\n\t// 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the\n\t// origin-only flag set to true.\n\tlet referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);\n\n\t// 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set\n\t// referrerURL to referrerOrigin.\n\tif (referrerURL.toString().length > 4096) {\n\t\treferrerURL = referrerOrigin;\n\t}\n\n\t// 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary\n\t// policy considerations in the interests of minimizing data leakage. For example, the user\n\t// agent could strip the URL down to an origin, modify its host, replace it with an empty\n\t// string, etc.\n\tif (referrerURLCallback) {\n\t\treferrerURL = referrerURLCallback(referrerURL);\n\t}\n\n\tif (referrerOriginCallback) {\n\t\treferrerOrigin = referrerOriginCallback(referrerOrigin);\n\t}\n\n\t// 8.Execute the statements corresponding to the value of policy:\n\tconst currentURL = new URL(request.url);\n\n\tswitch (policy) {\n\t\tcase 'no-referrer':\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin':\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'unsafe-url':\n\t\t\treturn referrerURL;\n\n\t\tcase 'strict-origin':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerOrigin.\n\t\t\treturn referrerOrigin.toString();\n\n\t\tcase 'strict-origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 3. Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'same-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. Return no referrer.\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'no-referrer-when-downgrade':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerURL.\n\t\t\treturn referrerURL;\n\n\t\tdefault:\n\t\t\tthrow new TypeError(`Invalid referrerPolicy: ${policy}`);\n\t}\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy \u00A78.1. Parse a referrer policy from a Referrer-Policy header}\n * @param {Headers} headers Response headers\n * @returns {string} policy\n */\nexport function parseReferrerPolicyFromHeader(headers) {\n\t// 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy`\n\t// and response\u2019s header list.\n\tconst policyTokens = (headers.get('referrer-policy') || '').split(/[,\\s]+/);\n\n\t// 2. Let policy be the empty string.\n\tlet policy = '';\n\n\t// 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty\n\t// string, then set policy to token.\n\t// Note: This algorithm loops over multiple policy values to allow deployment of new policy\n\t// values with fallbacks for older user agents, as described in \u00A7 11.1 Unknown Policy Values.\n\tfor (const token of policyTokens) {\n\t\tif (token && ReferrerPolicy.has(token)) {\n\t\t\tpolicy = token;\n\t\t}\n\t}\n\n\t// 4. Return policy.\n\treturn policy;\n}\n", "/**\n * Request.js\n *\n * Request class contains server only options\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport {format as formatUrl} from 'node:url';\nimport {deprecate} from 'node:util';\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType, getTotalBytes} from './body.js';\nimport {isAbortSignal} from './utils/is.js';\nimport {getSearch} from './utils/get-search.js';\nimport {\n\tvalidateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY\n} from './utils/referrer.js';\n\nconst INTERNALS = Symbol('Request internals');\n\n/**\n * Check if `obj` is an instance of Request.\n *\n * @param {*} object\n * @return {boolean}\n */\nconst isRequest = object => {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object[INTERNALS] === 'object'\n\t);\n};\n\nconst doBadDataWarn = deprecate(() => {},\n\t'.data is not a valid RequestInit property, use .body instead',\n\t'https://github.com/node-fetch/node-fetch/issues/1000 (request)');\n\n/**\n * Request class\n *\n * Ref: https://fetch.spec.whatwg.org/#request-class\n *\n * @param Mixed input Url or Request instance\n * @param Object init Custom options\n * @return Void\n */\nexport default class Request extends Body {\n\tconstructor(input, init = {}) {\n\t\tlet parsedURL;\n\n\t\t// Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)\n\t\tif (isRequest(input)) {\n\t\t\tparsedURL = new URL(input.url);\n\t\t} else {\n\t\t\tparsedURL = new URL(input);\n\t\t\tinput = {};\n\t\t}\n\n\t\tif (parsedURL.username !== '' || parsedURL.password !== '') {\n\t\t\tthrow new TypeError(`${parsedURL} is an url with embedded credentials.`);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tif (/^(delete|get|head|options|post|put)$/i.test(method)) {\n\t\t\tmethod = method.toUpperCase();\n\t\t}\n\n\t\tif (!isRequest(init) && 'data' in init) {\n\t\t\tdoBadDataWarn();\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif ((init.body != null || (isRequest(input) && input.body !== null)) &&\n\t\t\t(method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tconst inputBody = init.body ?\n\t\t\tinit.body :\n\t\t\t(isRequest(input) && input.body !== null ?\n\t\t\t\tclone(input) :\n\t\t\t\tnull);\n\n\t\tsuper(inputBody, {\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.set('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ?\n\t\t\tinput.signal :\n\t\t\tnull;\n\t\tif ('signal' in init) {\n\t\t\tsignal = init.signal;\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');\n\t\t}\n\n\t\t// \u00A75.4, Request constructor steps, step 15.1\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tlet referrer = init.referrer == null ? input.referrer : init.referrer;\n\t\tif (referrer === '') {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.2\n\t\t\treferrer = 'no-referrer';\n\t\t} else if (referrer) {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.1, 15.3.2\n\t\t\tconst parsedReferrer = new URL(referrer);\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.3, 15.3.4\n\t\t\treferrer = /^about:(\\/\\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer;\n\t\t} else {\n\t\t\treferrer = undefined;\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal,\n\t\t\treferrer\n\t\t};\n\n\t\t// Node-fetch-only options\n\t\tthis.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;\n\t\tthis.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t\tthis.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;\n\t\tthis.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;\n\n\t\t// \u00A75.4, Request constructor steps, step 16.\n\t\t// Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy\n\t\tthis.referrerPolicy = init.referrerPolicy || input.referrerPolicy || '';\n\t}\n\n\t/** @returns {string} */\n\tget method() {\n\t\treturn this[INTERNALS].method;\n\t}\n\n\t/** @returns {string} */\n\tget url() {\n\t\treturn formatUrl(this[INTERNALS].parsedURL);\n\t}\n\n\t/** @returns {Headers} */\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS].redirect;\n\t}\n\n\t/** @returns {AbortSignal} */\n\tget signal() {\n\t\treturn this[INTERNALS].signal;\n\t}\n\n\t// https://fetch.spec.whatwg.org/#dom-request-referrer\n\tget referrer() {\n\t\tif (this[INTERNALS].referrer === 'no-referrer') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer === 'client') {\n\t\t\treturn 'about:client';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer) {\n\t\t\treturn this[INTERNALS].referrer.toString();\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tget referrerPolicy() {\n\t\treturn this[INTERNALS].referrerPolicy;\n\t}\n\n\tset referrerPolicy(referrerPolicy) {\n\t\tthis[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);\n\t}\n\n\t/**\n\t * Clone this request\n\t *\n\t * @return Request\n\t */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Request';\n\t}\n}\n\nObject.defineProperties(Request.prototype, {\n\tmethod: {enumerable: true},\n\turl: {enumerable: true},\n\theaders: {enumerable: true},\n\tredirect: {enumerable: true},\n\tclone: {enumerable: true},\n\tsignal: {enumerable: true},\n\treferrer: {enumerable: true},\n\treferrerPolicy: {enumerable: true}\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param {Request} request - A Request instance\n * @return The options object to be passed to http.request\n */\nexport const getNodeRequestOptions = request => {\n\tconst {parsedURL} = request[INTERNALS];\n\tconst headers = new Headers(request[INTERNALS].headers);\n\n\t// Fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body === null && /^(post|put)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\n\tif (request.body !== null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\t// Set Content-Length if totalBytes is a number (that is not NaN)\n\t\tif (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// 4.1. Main fetch, step 2.6\n\t// > If request's referrer policy is the empty string, then set request's referrer policy to the\n\t// > default referrer policy.\n\tif (request.referrerPolicy === '') {\n\t\trequest.referrerPolicy = DEFAULT_REFERRER_POLICY;\n\t}\n\n\t// 4.1. Main fetch, step 2.7\n\t// > If request's referrer is not \"no-referrer\", set request's referrer to the result of invoking\n\t// > determine request's referrer.\n\tif (request.referrer && request.referrer !== 'no-referrer') {\n\t\trequest[INTERNALS].referrer = determineRequestsReferrer(request);\n\t} else {\n\t\trequest[INTERNALS].referrer = 'no-referrer';\n\t}\n\n\t// 4.5. HTTP-network-or-cache fetch, step 6.9\n\t// > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized\n\t// > and isomorphic encoded, to httpRequest's header list.\n\tif (request[INTERNALS].referrer instanceof URL) {\n\t\theaders.set('Referer', request.referrer);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip, deflate, br');\n\t}\n\n\tlet {agent} = request;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\tconst search = getSearch(parsedURL);\n\n\t// Pass the full URL directly to request(), but overwrite the following\n\t// options:\n\tconst options = {\n\t\t// Overwrite search to retain trailing ? (issue #776)\n\t\tpath: parsedURL.pathname + search,\n\t\t// The following options are not expressed in the URL\n\t\tmethod: request.method,\n\t\theaders: headers[Symbol.for('nodejs.util.inspect.custom')](),\n\t\tinsecureHTTPParser: request.insecureHTTPParser,\n\t\tagent\n\t};\n\n\treturn {\n\t\t/** @type {URL} */\n\t\tparsedURL,\n\t\toptions\n\t};\n};\n", "import {FetchBaseError} from './base.js';\n\n/**\n * AbortError interface for cancelled requests\n */\nexport class AbortError extends FetchBaseError {\n\tconstructor(message, type = 'aborted') {\n\t\tsuper(message, type);\n\t}\n}\n", "/**\n * Index.js\n *\n * a request API compatible with window.fetch\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport http from 'node:http';\nimport https from 'node:https';\nimport zlib from 'node:zlib';\nimport Stream, {PassThrough, pipeline as pump} from 'node:stream';\nimport {Buffer} from 'node:buffer';\n\nimport dataUriToBuffer from 'data-uri-to-buffer';\n\nimport {writeToStream, clone} from './body.js';\nimport Response from './response.js';\nimport Headers, {fromRawHeaders} from './headers.js';\nimport Request, {getNodeRequestOptions} from './request.js';\nimport {FetchError} from './errors/fetch-error.js';\nimport {AbortError} from './errors/abort-error.js';\nimport {isRedirect} from './utils/is-redirect.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\nimport {isDomainOrSubdomain, isSameProtocol} from './utils/is.js';\nimport {parseReferrerPolicyFromHeader} from './utils/referrer.js';\nimport {\n\tBlob,\n\tFile,\n\tfileFromSync,\n\tfileFrom,\n\tblobFromSync,\n\tblobFrom\n} from 'fetch-blob/from.js';\n\nexport {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect};\nexport {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom};\n\nconst supportedSchemas = new Set(['data:', 'http:', 'https:']);\n\n/**\n * Fetch function\n *\n * @param {string | URL | import('./request').default} url - Absolute url or Request instance\n * @param {*} [options_] - Fetch options\n * @return {Promise}\n */\nexport default async function fetch(url, options_) {\n\treturn new Promise((resolve, reject) => {\n\t\t// Build request object\n\t\tconst request = new Request(url, options_);\n\t\tconst {parsedURL, options} = getNodeRequestOptions(request);\n\t\tif (!supportedSchemas.has(parsedURL.protocol)) {\n\t\t\tthrow new TypeError(`node-fetch cannot load ${url}. URL scheme \"${parsedURL.protocol.replace(/:$/, '')}\" is not supported.`);\n\t\t}\n\n\t\tif (parsedURL.protocol === 'data:') {\n\t\t\tconst data = dataUriToBuffer(request.url);\n\t\t\tconst response = new Response(data, {headers: {'Content-Type': data.typeFull}});\n\t\t\tresolve(response);\n\t\t\treturn;\n\t\t}\n\n\t\t// Wrap http.request into fetch\n\t\tconst send = (parsedURL.protocol === 'https:' ? https : http).request;\n\t\tconst {signal} = request;\n\t\tlet response = null;\n\n\t\tconst abort = () => {\n\t\t\tconst error = new AbortError('The operation was aborted.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\trequest.body.destroy(error);\n\t\t\t}\n\n\t\t\tif (!response || !response.body) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = () => {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// Send request\n\t\tconst request_ = send(parsedURL.toString(), options);\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tconst finalize = () => {\n\t\t\trequest_.abort();\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t}\n\t\t};\n\n\t\trequest_.on('error', error => {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));\n\t\t\tfinalize();\n\t\t});\n\n\t\tfixResponseChunkedTransferBadEnding(request_, error => {\n\t\t\tif (response && response.body) {\n\t\t\t\tresponse.body.destroy(error);\n\t\t\t}\n\t\t});\n\n\t\t/* c8 ignore next 18 */\n\t\tif (process.version < 'v14') {\n\t\t\t// Before Node.js 14, pipeline() does not fully support async iterators and does not always\n\t\t\t// properly handle when the socket close/end events are out of order.\n\t\t\trequest_.on('socket', s => {\n\t\t\t\tlet endedWithEventsCount;\n\t\t\t\ts.prependListener('end', () => {\n\t\t\t\t\tendedWithEventsCount = s._eventsCount;\n\t\t\t\t});\n\t\t\t\ts.prependListener('close', hadError => {\n\t\t\t\t\t// if end happened before close but the socket didn't emit an error, do it now\n\t\t\t\t\tif (response && endedWithEventsCount < s._eventsCount && !hadError) {\n\t\t\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\t\t\tresponse.body.emit('error', error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\trequest_.on('response', response_ => {\n\t\t\trequest_.setTimeout(0);\n\t\t\tconst headers = fromRawHeaders(response_.rawHeaders);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (isRedirect(response_.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tlet locationURL = null;\n\t\t\t\ttry {\n\t\t\t\t\tlocationURL = location === null ? null : new URL(location, request.url);\n\t\t\t\t} catch {\n\t\t\t\t\t// error here can only be invalid URL in Location: header\n\t\t\t\t\t// do not throw when options.redirect == manual\n\t\t\t\t\t// let the user extract the errorneous redirect URL\n\t\t\t\t\tif (request.redirect !== 'manual') {\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// Nothing to do\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow': {\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOptions = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: clone(request),\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\tsize: request.size,\n\t\t\t\t\t\t\treferrer: request.referrer,\n\t\t\t\t\t\t\treferrerPolicy: request.referrerPolicy\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// when forwarding sensitive headers like \"Authorization\",\n\t\t\t\t\t\t// \"WWW-Authenticate\", and \"Cookie\" to untrusted targets,\n\t\t\t\t\t\t// headers will be ignored when following a redirect to a domain\n\t\t\t\t\t\t// that is not a subdomain match or exact match of the initial domain.\n\t\t\t\t\t\t// For example, a redirect from \"foo.com\" to either \"foo.com\" or \"sub.foo.com\"\n\t\t\t\t\t\t// will forward the sensitive headers, but a redirect to \"bar.com\" will not.\n\t\t\t\t\t\t// headers will also be ignored when following a redirect to a domain using\n\t\t\t\t\t\t// a different protocol. For example, a redirect from \"https://foo.com\" to \"http://foo.com\"\n\t\t\t\t\t\t// will not forward the sensitive headers\n\t\t\t\t\t\tif (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {\n\t\t\t\t\t\t\tfor (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {\n\t\t\t\t\t\t\t\trequestOptions.headers.delete(name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) {\n\t\t\t\t\t\t\trequestOptions.method = 'GET';\n\t\t\t\t\t\t\trequestOptions.body = undefined;\n\t\t\t\t\t\t\trequestOptions.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 14\n\t\t\t\t\t\tconst responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);\n\t\t\t\t\t\tif (responseReferrerPolicy) {\n\t\t\t\t\t\t\trequestOptions.referrerPolicy = responseReferrerPolicy;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOptions)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Prepare response\n\t\t\tif (signal) {\n\t\t\t\tresponse_.once('end', () => {\n\t\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet body = pump(response_, new PassThrough(), error => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\t// see https://github.com/nodejs/node/pull/29376\n\t\t\t/* c8 ignore next 3 */\n\t\t\tif (process.version < 'v12.10') {\n\t\t\t\tresponse_.on('aborted', abortAndFinalize);\n\t\t\t}\n\n\t\t\tconst responseOptions = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: response_.statusCode,\n\t\t\t\tstatusText: response_.statusMessage,\n\t\t\t\theaders,\n\t\t\t\tsize: request.size,\n\t\t\t\tcounter: request.counter,\n\t\t\t\thighWaterMark: request.highWaterMark\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// For gzip\n\t\t\tif (codings === 'gzip' || codings === 'x-gzip') {\n\t\t\t\tbody = pump(body, zlib.createGunzip(zlibOptions), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For deflate\n\t\t\tif (codings === 'deflate' || codings === 'x-deflate') {\n\t\t\t\t// Handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = pump(response_, new PassThrough(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\traw.once('data', chunk => {\n\t\t\t\t\t// See http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflate(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflateRaw(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\traw.once('end', () => {\n\t\t\t\t\t// Some old IIS servers return zero-length OK deflate responses, so\n\t\t\t\t\t// 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903\n\t\t\t\t\tif (!response) {\n\t\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For br\n\t\t\tif (codings === 'br') {\n\t\t\t\tbody = pump(body, zlib.createBrotliDecompress(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise, use response as-is\n\t\t\tresponse = new Response(body, responseOptions);\n\t\t\tresolve(response);\n\t\t});\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\twriteToStream(request_, request).catch(reject);\n\t});\n}\n\nfunction fixResponseChunkedTransferBadEnding(request, errorCallback) {\n\tconst LAST_CHUNK = Buffer.from('0\\r\\n\\r\\n');\n\n\tlet isChunkedTransfer = false;\n\tlet properLastChunkReceived = false;\n\tlet previousChunk;\n\n\trequest.on('response', response => {\n\t\tconst {headers} = response;\n\t\tisChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length'];\n\t});\n\n\trequest.on('socket', socket => {\n\t\tconst onSocketClose = () => {\n\t\t\tif (isChunkedTransfer && !properLastChunkReceived) {\n\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\terrorCallback(error);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = buf => {\n\t\t\tproperLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;\n\n\t\t\t// Sometimes final 0-length chunk and end of message code are in separate packets\n\t\t\tif (!properLastChunkReceived && previousChunk) {\n\t\t\t\tproperLastChunkReceived = (\n\t\t\t\t\tBuffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&\n\t\t\t\t\tBuffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tpreviousChunk = buf;\n\t\t};\n\n\t\tsocket.prependListener('close', onSocketClose);\n\t\tsocket.on('data', onData);\n\n\t\trequest.on('close', () => {\n\t\t\tsocket.removeListener('close', onSocketClose);\n\t\t\tsocket.removeListener('data', onData);\n\t\t});\n\t});\n}\n", null, null, ";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.3.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2025 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // The index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return \u00B10 if x is \u00B10 or y is \u00B1Infinity, or return \u00B1Infinity as y is \u00B10.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne + (id === 2 && e > ne);\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on \u00B1Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and \u00B1Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, \u00B1Infinity, \u00B10 or \u00B11, or n is \u00B1Infinity, NaN or \u00B10.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to \u00B1Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to \u00B1Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to \u00B10: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = \u00B1Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return \u00B10, else return \u00B1Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, \u00B1Infinity or \u00B10?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return \u00B1Infinity if either is \u00B1Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return \u00B10 if either is \u00B10.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return \u00B1Infinity if either \u00B1Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n", "var BigNumber = require('bignumber.js');\n\n/*\n json2.js\n 2013-05-26\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n See http://www.JSON.org/js.html\n\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n\n\n This file creates a global JSON object containing two methods: stringify\n and parse.\n\n JSON.stringify(value, replacer, space)\n value any JavaScript value, usually an object or array.\n\n replacer an optional parameter that determines how object\n values are stringified for objects. It can be a\n function or an array of strings.\n\n space an optional parameter that specifies the indentation\n of nested structures. If it is omitted, the text will\n be packed without extra whitespace. If it is a number,\n it will specify the number of spaces to indent at each\n level. If it is a string (such as '\\t' or ' '),\n it contains the characters used to indent at each level.\n\n This method produces a JSON text from a JavaScript value.\n\n When an object value is found, if the object contains a toJSON\n method, its toJSON method will be called and the result will be\n stringified. A toJSON method does not serialize: it returns the\n value represented by the name/value pair that should be serialized,\n or undefined if nothing should be serialized. The toJSON method\n will be passed the key associated with the value, and this will be\n bound to the value\n\n For example, this would serialize Dates as ISO strings.\n\n Date.prototype.toJSON = function (key) {\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n return this.getUTCFullYear() + '-' +\n f(this.getUTCMonth() + 1) + '-' +\n f(this.getUTCDate()) + 'T' +\n f(this.getUTCHours()) + ':' +\n f(this.getUTCMinutes()) + ':' +\n f(this.getUTCSeconds()) + 'Z';\n };\n\n You can provide an optional replacer method. It will be passed the\n key and value of each member, with this bound to the containing\n object. The value that is returned from your method will be\n serialized. If your method returns undefined, then the member will\n be excluded from the serialization.\n\n If the replacer parameter is an array of strings, then it will be\n used to select the members to be serialized. It filters the results\n such that only members with keys listed in the replacer array are\n stringified.\n\n Values that do not have JSON representations, such as undefined or\n functions, will not be serialized. Such values in objects will be\n dropped; in arrays they will be replaced with null. You can use\n a replacer function to replace those with JSON values.\n JSON.stringify(undefined) returns undefined.\n\n The optional space parameter produces a stringification of the\n value that is filled with line breaks and indentation to make it\n easier to read.\n\n If the space parameter is a non-empty string, then that string will\n be used for indentation. If the space parameter is a number, then\n the indentation will be that many spaces.\n\n Example:\n\n text = JSON.stringify(['e', {pluribus: 'unum'}]);\n // text is '[\"e\",{\"pluribus\":\"unum\"}]'\n\n\n text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\\t');\n // text is '[\\n\\t\"e\",\\n\\t{\\n\\t\\t\"pluribus\": \"unum\"\\n\\t}\\n]'\n\n text = JSON.stringify([new Date()], function (key, value) {\n return this[key] instanceof Date ?\n 'Date(' + this[key] + ')' : value;\n });\n // text is '[\"Date(---current time---)\"]'\n\n\n JSON.parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = JSON.parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n myData = JSON.parse('[\"Date(09/09/2001)\"]', function (key, value) {\n var d;\n if (typeof value === 'string' &&\n value.slice(0, 5) === 'Date(' &&\n value.slice(-1) === ')') {\n d = new Date(value.slice(5, -1));\n if (d) {\n return d;\n }\n }\n return value;\n });\n\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n*/\n\n/*jslint evil: true, regexp: true */\n\n/*members \"\", \"\\b\", \"\\t\", \"\\n\", \"\\f\", \"\\r\", \"\\\"\", JSON, \"\\\\\", apply,\n call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,\n getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,\n lastIndex, length, parse, prototype, push, replace, slice, stringify,\n test, toJSON, toString, valueOf\n*/\n\n\n// Create a JSON object only if one does not already exist. We create the\n// methods in a closure to avoid creating global variables.\n\nvar JSON = module.exports;\n\n(function () {\n 'use strict';\n\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n var cx = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n escapable = /[\\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n gap,\n indent,\n meta = { // table of character substitutions\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n '\"' : '\\\\\"',\n '\\\\': '\\\\\\\\'\n },\n rep;\n\n\n function quote(string) {\n\n// If the string contains no control characters, no quote characters, and no\n// backslash characters, then we can safely slap some quotes around it.\n// Otherwise we must also replace the offending characters with safe escape\n// sequences.\n\n escapable.lastIndex = 0;\n return escapable.test(string) ? '\"' + string.replace(escapable, function (a) {\n var c = meta[a];\n return typeof c === 'string'\n ? c\n : '\\\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);\n }) + '\"' : '\"' + string + '\"';\n }\n\n\n function str(key, holder) {\n\n// Produce a string from holder[key].\n\n var i, // The loop counter.\n k, // The member key.\n v, // The member value.\n length,\n mind = gap,\n partial,\n value = holder[key],\n isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));\n\n// If the value has a toJSON method, call it to obtain a replacement value.\n\n if (value && typeof value === 'object' &&\n typeof value.toJSON === 'function') {\n value = value.toJSON(key);\n }\n\n// If we were called with a replacer function, then call the replacer to\n// obtain a replacement value.\n\n if (typeof rep === 'function') {\n value = rep.call(holder, key, value);\n }\n\n// What happens next depends on the value's type.\n\n switch (typeof value) {\n case 'string':\n if (isBigNumber) {\n return value;\n } else {\n return quote(value);\n }\n\n case 'number':\n\n// JSON numbers must be finite. Encode non-finite numbers as null.\n\n return isFinite(value) ? String(value) : 'null';\n\n case 'boolean':\n case 'null':\n case 'bigint':\n\n// If the value is a boolean or null, convert it to a string. Note:\n// typeof null does not produce 'null'. The case is included here in\n// the remote chance that this gets fixed someday.\n\n return String(value);\n\n// If the type is 'object', we might be dealing with an object or an array or\n// null.\n\n case 'object':\n\n// Due to a specification blunder in ECMAScript, typeof null is 'object',\n// so watch out for that case.\n\n if (!value) {\n return 'null';\n }\n\n// Make an array to hold the partial results of stringifying this object value.\n\n gap += indent;\n partial = [];\n\n// Is the value an array?\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n\n// The value is an array. Stringify every element. Use null as a placeholder\n// for non-JSON values.\n\n length = value.length;\n for (i = 0; i < length; i += 1) {\n partial[i] = str(i, value) || 'null';\n }\n\n// Join all of the elements together, separated with commas, and wrap them in\n// brackets.\n\n v = partial.length === 0\n ? '[]'\n : gap\n ? '[\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + ']'\n : '[' + partial.join(',') + ']';\n gap = mind;\n return v;\n }\n\n// If the replacer is an array, use it to select the members to be stringified.\n\n if (rep && typeof rep === 'object') {\n length = rep.length;\n for (i = 0; i < length; i += 1) {\n if (typeof rep[i] === 'string') {\n k = rep[i];\n v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n }\n }\n } else {\n\n// Otherwise, iterate through all of the keys in the object.\n\n Object.keys(value).forEach(function(k) {\n var v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n });\n }\n\n// Join all of the member texts together, separated with commas,\n// and wrap them in braces.\n\n v = partial.length === 0\n ? '{}'\n : gap\n ? '{\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + '}'\n : '{' + partial.join(',') + '}';\n gap = mind;\n return v;\n }\n }\n\n// If the JSON object does not yet have a stringify method, give it one.\n\n if (typeof JSON.stringify !== 'function') {\n JSON.stringify = function (value, replacer, space) {\n\n// The stringify method takes a value and an optional replacer, and an optional\n// space parameter, and returns a JSON text. The replacer can be a function\n// that can replace values, or an array of strings that will select the keys.\n// A default replacer method can be provided. Use of the space parameter can\n// produce text that is more easily readable.\n\n var i;\n gap = '';\n indent = '';\n\n// If the space parameter is a number, make an indent string containing that\n// many spaces.\n\n if (typeof space === 'number') {\n for (i = 0; i < space; i += 1) {\n indent += ' ';\n }\n\n// If the space parameter is a string, it will be used as the indent string.\n\n } else if (typeof space === 'string') {\n indent = space;\n }\n\n// If there is a replacer, it must be a function or an array.\n// Otherwise, throw an error.\n\n rep = replacer;\n if (replacer && typeof replacer !== 'function' &&\n (typeof replacer !== 'object' ||\n typeof replacer.length !== 'number')) {\n throw new Error('JSON.stringify');\n }\n\n// Make a fake root object containing our value under the key of ''.\n// Return the result of stringifying the value.\n\n return str('', {'': value});\n };\n }\n}());\n", "var BigNumber = null;\n\n// regexpxs extracted from\n// (c) BSD-3-Clause\n// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors\n\nconst suspectProtoRx = /(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])/;\nconst suspectConstructorRx = /(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)/;\n\n/*\n json_parse.js\n 2012-06-20\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n This file creates a json_parse function.\n During create you can (optionally) specify some behavioural switches\n\n require('json-bigint')(options)\n\n The optional options parameter holds switches that drive certain\n aspects of the parsing process:\n * options.strict = true will warn about duplicate-key usage in the json.\n The default (strict = false) will silently ignore those and overwrite\n values for keys that are in duplicate use.\n\n The resulting function follows this signature:\n json_parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = json_parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n*/\n\n/*members \"\", \"\\\"\", \"\\/\", \"\\\\\", at, b, call, charAt, f, fromCharCode,\n hasOwnProperty, message, n, name, prototype, push, r, t, text\n*/\n\nvar json_parse = function (options) {\n 'use strict';\n\n // This is a function that can parse a JSON text, producing a JavaScript\n // data structure. It is a simple, recursive descent parser. It does not use\n // eval or regular expressions, so it can be used as a model for implementing\n // a JSON parser in other languages.\n\n // We are defining the function inside of another function to avoid creating\n // global variables.\n\n // Default options one can override by passing options to the parse()\n var _options = {\n strict: false, // not being strict means do not generate syntax errors for \"duplicate key\"\n storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string\n alwaysParseAsBig: false, // toggles whether all numbers should be Big\n useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js\n protoAction: 'error',\n constructorAction: 'error',\n };\n\n // If there are options, then use them to override the default _options\n if (options !== undefined && options !== null) {\n if (options.strict === true) {\n _options.strict = true;\n }\n if (options.storeAsString === true) {\n _options.storeAsString = true;\n }\n _options.alwaysParseAsBig =\n options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;\n _options.useNativeBigInt =\n options.useNativeBigInt === true ? options.useNativeBigInt : false;\n\n if (typeof options.constructorAction !== 'undefined') {\n if (\n options.constructorAction === 'error' ||\n options.constructorAction === 'ignore' ||\n options.constructorAction === 'preserve'\n ) {\n _options.constructorAction = options.constructorAction;\n } else {\n throw new Error(\n `Incorrect value for constructorAction option, must be \"error\", \"ignore\" or undefined but passed ${options.constructorAction}`\n );\n }\n }\n\n if (typeof options.protoAction !== 'undefined') {\n if (\n options.protoAction === 'error' ||\n options.protoAction === 'ignore' ||\n options.protoAction === 'preserve'\n ) {\n _options.protoAction = options.protoAction;\n } else {\n throw new Error(\n `Incorrect value for protoAction option, must be \"error\", \"ignore\" or undefined but passed ${options.protoAction}`\n );\n }\n }\n }\n\n var at, // The index of the current character\n ch, // The current character\n escapee = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n },\n text,\n error = function (m) {\n // Call error when something is wrong.\n\n throw {\n name: 'SyntaxError',\n message: m,\n at: at,\n text: text,\n };\n },\n next = function (c) {\n // If a c parameter is provided, verify that it matches the current character.\n\n if (c && c !== ch) {\n error(\"Expected '\" + c + \"' instead of '\" + ch + \"'\");\n }\n\n // Get the next character. When there are no more characters,\n // return the empty string.\n\n ch = text.charAt(at);\n at += 1;\n return ch;\n },\n number = function () {\n // Parse a number value.\n\n var number,\n string = '';\n\n if (ch === '-') {\n string = '-';\n next('-');\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n if (ch === '.') {\n string += '.';\n while (next() && ch >= '0' && ch <= '9') {\n string += ch;\n }\n }\n if (ch === 'e' || ch === 'E') {\n string += ch;\n next();\n if (ch === '-' || ch === '+') {\n string += ch;\n next();\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n }\n number = +string;\n if (!isFinite(number)) {\n error('Bad number');\n } else {\n if (BigNumber == null) BigNumber = require('bignumber.js');\n //if (number > 9007199254740992 || number < -9007199254740992)\n // Bignumber has stricter check: everything with length > 15 digits disallowed\n if (string.length > 15)\n return _options.storeAsString\n ? string\n : _options.useNativeBigInt\n ? BigInt(string)\n : new BigNumber(string);\n else\n return !_options.alwaysParseAsBig\n ? number\n : _options.useNativeBigInt\n ? BigInt(number)\n : new BigNumber(number);\n }\n },\n string = function () {\n // Parse a string value.\n\n var hex,\n i,\n string = '',\n uffff;\n\n // When parsing for string values, we must look for \" and \\ characters.\n\n if (ch === '\"') {\n var startAt = at;\n while (next()) {\n if (ch === '\"') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n return string;\n }\n if (ch === '\\\\') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n if (ch === 'u') {\n uffff = 0;\n for (i = 0; i < 4; i += 1) {\n hex = parseInt(next(), 16);\n if (!isFinite(hex)) {\n break;\n }\n uffff = uffff * 16 + hex;\n }\n string += String.fromCharCode(uffff);\n } else if (typeof escapee[ch] === 'string') {\n string += escapee[ch];\n } else {\n break;\n }\n startAt = at;\n }\n }\n }\n error('Bad string');\n },\n white = function () {\n // Skip whitespace.\n\n while (ch && ch <= ' ') {\n next();\n }\n },\n word = function () {\n // true, false, or null.\n\n switch (ch) {\n case 't':\n next('t');\n next('r');\n next('u');\n next('e');\n return true;\n case 'f':\n next('f');\n next('a');\n next('l');\n next('s');\n next('e');\n return false;\n case 'n':\n next('n');\n next('u');\n next('l');\n next('l');\n return null;\n }\n error(\"Unexpected '\" + ch + \"'\");\n },\n value, // Place holder for the value function.\n array = function () {\n // Parse an array value.\n\n var array = [];\n\n if (ch === '[') {\n next('[');\n white();\n if (ch === ']') {\n next(']');\n return array; // empty array\n }\n while (ch) {\n array.push(value());\n white();\n if (ch === ']') {\n next(']');\n return array;\n }\n next(',');\n white();\n }\n }\n error('Bad array');\n },\n object = function () {\n // Parse an object value.\n\n var key,\n object = Object.create(null);\n\n if (ch === '{') {\n next('{');\n white();\n if (ch === '}') {\n next('}');\n return object; // empty object\n }\n while (ch) {\n key = string();\n white();\n next(':');\n if (\n _options.strict === true &&\n Object.hasOwnProperty.call(object, key)\n ) {\n error('Duplicate key \"' + key + '\"');\n }\n\n if (suspectProtoRx.test(key) === true) {\n if (_options.protoAction === 'error') {\n error('Object contains forbidden prototype property');\n } else if (_options.protoAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else if (suspectConstructorRx.test(key) === true) {\n if (_options.constructorAction === 'error') {\n error('Object contains forbidden constructor property');\n } else if (_options.constructorAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else {\n object[key] = value();\n }\n\n white();\n if (ch === '}') {\n next('}');\n return object;\n }\n next(',');\n white();\n }\n }\n error('Bad object');\n };\n\n value = function () {\n // Parse a JSON value. It could be an object, an array, a string, a number,\n // or a word.\n\n white();\n switch (ch) {\n case '{':\n return object();\n case '[':\n return array();\n case '\"':\n return string();\n case '-':\n return number();\n default:\n return ch >= '0' && ch <= '9' ? number() : word();\n }\n };\n\n // Return the json_parse function. It will have access to all of the above\n // functions and variables.\n\n return function (source, reviver) {\n var result;\n\n text = source + '';\n at = 0;\n ch = ' ';\n result = value();\n white();\n if (ch) {\n error('Syntax error');\n }\n\n // If there is a reviver function, we recursively walk the new structure,\n // passing each name/value pair to the reviver function for possible\n // transformation, starting with a temporary root object that holds the result\n // in an empty key. If there is not a reviver function, we simply return the\n // result.\n\n return typeof reviver === 'function'\n ? (function walk(holder, key) {\n var k,\n v,\n value = holder[key];\n if (value && typeof value === 'object') {\n Object.keys(value).forEach(function (k) {\n v = walk(value, k);\n if (v !== undefined) {\n value[k] = v;\n } else {\n delete value[k];\n }\n });\n }\n return reviver.call(holder, key, value);\n })({ '': result }, '')\n : result;\n };\n};\n\nmodule.exports = json_parse;\n", "var json_stringify = require('./lib/stringify.js').stringify;\nvar json_parse = require('./lib/parse.js');\n\nmodule.exports = function(options) {\n return {\n parse: json_parse(options),\n stringify: json_stringify\n }\n};\n//create the default method members with no options applied for backwards compatibility\nmodule.exports.parse = json_parse();\nmodule.exports.stringify = json_stringify;\n", null, null, null, null, null, "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.fromArrayBufferToHex = fromArrayBufferToHex;\n/**\n * Converts an ArrayBuffer to a hexadecimal string.\n * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.\n * @return The hexadecimal encoding of the ArrayBuffer.\n */\nfunction fromArrayBufferToHex(arrayBuffer) {\n // Convert buffer to byte array.\n const byteArray = Array.from(new Uint8Array(arrayBuffer));\n // Convert bytes to hex string.\n return byteArray\n .map(byte => {\n return byte.toString(16).padStart(2, '0');\n })\n .join('');\n}\n//# sourceMappingURL=shared.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserCrypto = void 0;\n// This file implements crypto functions we need using in-browser\n// SubtleCrypto interface `window.crypto.subtle`.\nconst base64js = require(\"base64-js\");\nconst shared_1 = require(\"../shared\");\nclass BrowserCrypto {\n constructor() {\n if (typeof window === 'undefined' ||\n window.crypto === undefined ||\n window.crypto.subtle === undefined) {\n throw new Error(\"SubtleCrypto not found. Make sure it's an https:// website.\");\n }\n }\n async sha256DigestBase64(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return base64js.fromByteArray(new Uint8Array(outputBuffer));\n }\n randomBytesBase64(count) {\n const array = new Uint8Array(count);\n window.crypto.getRandomValues(array);\n return base64js.fromByteArray(array);\n }\n static padBase64(base64) {\n // base64js requires padding, so let's add some '='\n while (base64.length % 4 !== 0) {\n base64 += '=';\n }\n return base64;\n }\n async verify(pubkey, data, signature) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));\n const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);\n // SubtleCrypto's verify method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);\n return result;\n }\n async sign(privateKey, data) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);\n // SubtleCrypto's sign method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);\n return base64js.fromByteArray(new Uint8Array(result));\n }\n decodeBase64StringUtf8(base64) {\n const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));\n const result = new TextDecoder().decode(uint8array);\n return result;\n }\n encodeBase64StringUtf8(text) {\n const uint8array = new TextEncoder().encode(text);\n const result = base64js.fromByteArray(uint8array);\n return result;\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return (0, shared_1.fromArrayBufferToHex)(outputBuffer);\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n // Convert key, if provided in ArrayBuffer format, to string.\n const rawKey = typeof key === 'string'\n ? key\n : String.fromCharCode(...new Uint16Array(key));\n const enc = new TextEncoder();\n const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {\n name: 'HMAC',\n hash: {\n name: 'SHA-256',\n },\n }, false, ['sign']);\n return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));\n }\n}\nexports.BrowserCrypto = BrowserCrypto;\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeCrypto = void 0;\nconst crypto = require(\"crypto\");\nclass NodeCrypto {\n async sha256DigestBase64(str) {\n return crypto.createHash('sha256').update(str).digest('base64');\n }\n randomBytesBase64(count) {\n return crypto.randomBytes(count).toString('base64');\n }\n async verify(pubkey, data, signature) {\n const verifier = crypto.createVerify('RSA-SHA256');\n verifier.update(data);\n verifier.end();\n return verifier.verify(pubkey, signature, 'base64');\n }\n async sign(privateKey, data) {\n const signer = crypto.createSign('RSA-SHA256');\n signer.update(data);\n signer.end();\n return signer.sign(privateKey, 'base64');\n }\n decodeBase64StringUtf8(base64) {\n return Buffer.from(base64, 'base64').toString('utf-8');\n }\n encodeBase64StringUtf8(text) {\n return Buffer.from(text, 'utf-8').toString('base64');\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n return crypto.createHash('sha256').update(str).digest('hex');\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n const cryptoKey = typeof key === 'string' ? key : toBuffer(key);\n return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());\n }\n}\nexports.NodeCrypto = NodeCrypto;\n/**\n * Converts a Node.js Buffer to an ArrayBuffer.\n * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer\n * @param buffer The Buffer input to covert.\n * @return The ArrayBuffer representation of the input.\n */\nfunction toArrayBuffer(buffer) {\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n}\n/**\n * Converts an ArrayBuffer to a Node.js Buffer.\n * @param arrayBuffer The ArrayBuffer input to covert.\n * @return The Buffer representation of the input.\n */\nfunction toBuffer(arrayBuffer) {\n return Buffer.from(arrayBuffer);\n}\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createCrypto = createCrypto;\nexports.hasBrowserCrypto = hasBrowserCrypto;\nconst crypto_1 = require(\"./browser/crypto\");\nconst crypto_2 = require(\"./node/crypto\");\n__exportStar(require(\"./shared\"), exports);\n// Crypto interface will provide required crypto functions.\n// Use `createCrypto()` factory function to create an instance\n// of Crypto. It will either use Node.js `crypto` module, or\n// use browser's SubtleCrypto interface. Since most of the\n// SubtleCrypto methods return promises, we must make those\n// methods return promises here as well, even though in Node.js\n// they are synchronous.\nfunction createCrypto() {\n if (hasBrowserCrypto()) {\n return new crypto_1.BrowserCrypto();\n }\n return new crypto_2.NodeCrypto();\n}\nfunction hasBrowserCrypto() {\n return (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.subtle !== 'undefined');\n}\n//# sourceMappingURL=crypto.js.map", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "'use strict';\n\nfunction getParamSize(keySize) {\n\tvar result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);\n\treturn result;\n}\n\nvar paramBytesForAlg = {\n\tES256: getParamSize(256),\n\tES384: getParamSize(384),\n\tES512: getParamSize(521)\n};\n\nfunction getParamBytesForAlg(alg) {\n\tvar paramBytes = paramBytesForAlg[alg];\n\tif (paramBytes) {\n\t\treturn paramBytes;\n\t}\n\n\tthrow new Error('Unknown algorithm \"' + alg + '\"');\n}\n\nmodule.exports = getParamBytesForAlg;\n", "'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar getParamBytesForAlg = require('./param-bytes-for-alg');\n\nvar MAX_OCTET = 0x80,\n\tCLASS_UNIVERSAL = 0,\n\tPRIMITIVE_BIT = 0x20,\n\tTAG_SEQ = 0x10,\n\tTAG_INT = 0x02,\n\tENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),\n\tENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);\n\nfunction base64Url(base64) {\n\treturn base64\n\t\t.replace(/=/g, '')\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_');\n}\n\nfunction signatureAsBuffer(signature) {\n\tif (Buffer.isBuffer(signature)) {\n\t\treturn signature;\n\t} else if ('string' === typeof signature) {\n\t\treturn Buffer.from(signature, 'base64');\n\t}\n\n\tthrow new TypeError('ECDSA signature must be a Base64 string or a Buffer');\n}\n\nfunction derToJose(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\t// the DER encoded param should at most be the param size, plus a padding\n\t// zero, since due to being a signed integer\n\tvar maxEncodedParamLength = paramBytes + 1;\n\n\tvar inputLength = signature.length;\n\n\tvar offset = 0;\n\tif (signature[offset++] !== ENCODED_TAG_SEQ) {\n\t\tthrow new Error('Could not find expected \"seq\"');\n\t}\n\n\tvar seqLength = signature[offset++];\n\tif (seqLength === (MAX_OCTET | 1)) {\n\t\tseqLength = signature[offset++];\n\t}\n\n\tif (inputLength - offset < seqLength) {\n\t\tthrow new Error('\"seq\" specified length of \"' + seqLength + '\", only \"' + (inputLength - offset) + '\" remaining');\n\t}\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"r\"');\n\t}\n\n\tvar rLength = signature[offset++];\n\n\tif (inputLength - offset - 2 < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", only \"' + (inputLength - offset - 2) + '\" available');\n\t}\n\n\tif (maxEncodedParamLength < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar rOffset = offset;\n\toffset += rLength;\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"s\"');\n\t}\n\n\tvar sLength = signature[offset++];\n\n\tif (inputLength - offset !== sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", expected \"' + (inputLength - offset) + '\"');\n\t}\n\n\tif (maxEncodedParamLength < sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar sOffset = offset;\n\toffset += sLength;\n\n\tif (offset !== inputLength) {\n\t\tthrow new Error('Expected to consume entire buffer, but \"' + (inputLength - offset) + '\" bytes remain');\n\t}\n\n\tvar rPadding = paramBytes - rLength,\n\t\tsPadding = paramBytes - sLength;\n\n\tvar dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);\n\n\tfor (offset = 0; offset < rPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);\n\n\toffset = paramBytes;\n\n\tfor (var o = offset; offset < o + sPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);\n\n\tdst = dst.toString('base64');\n\tdst = base64Url(dst);\n\n\treturn dst;\n}\n\nfunction countPadding(buf, start, stop) {\n\tvar padding = 0;\n\twhile (start + padding < stop && buf[start + padding] === 0) {\n\t\t++padding;\n\t}\n\n\tvar needsSign = buf[start + padding] >= MAX_OCTET;\n\tif (needsSign) {\n\t\t--padding;\n\t}\n\n\treturn padding;\n}\n\nfunction joseToDer(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\tvar signatureBytes = signature.length;\n\tif (signatureBytes !== paramBytes * 2) {\n\t\tthrow new TypeError('\"' + alg + '\" signatures must be \"' + paramBytes * 2 + '\" bytes, saw \"' + signatureBytes + '\"');\n\t}\n\n\tvar rPadding = countPadding(signature, 0, paramBytes);\n\tvar sPadding = countPadding(signature, paramBytes, signature.length);\n\tvar rLength = paramBytes - rPadding;\n\tvar sLength = paramBytes - sPadding;\n\n\tvar rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;\n\n\tvar shortLength = rsBytes < MAX_OCTET;\n\n\tvar dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);\n\n\tvar offset = 0;\n\tdst[offset++] = ENCODED_TAG_SEQ;\n\tif (shortLength) {\n\t\t// Bit 8 has value \"0\"\n\t\t// bits 7-1 give the length.\n\t\tdst[offset++] = rsBytes;\n\t} else {\n\t\t// Bit 8 of first octet has value \"1\"\n\t\t// bits 7-1 give the number of additional length octets.\n\t\tdst[offset++] = MAX_OCTET\t| 1;\n\t\t// length, base 256\n\t\tdst[offset++] = rsBytes & 0xff;\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = rLength;\n\tif (rPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\toffset += signature.copy(dst, offset, 0, paramBytes);\n\t} else {\n\t\toffset += signature.copy(dst, offset, rPadding, paramBytes);\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = sLength;\n\tif (sPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\tsignature.copy(dst, offset, paramBytes);\n\t} else {\n\t\tsignature.copy(dst, offset, paramBytes + sPadding);\n\t}\n\n\treturn dst;\n}\n\nmodule.exports = {\n\tderToJose: derToJose,\n\tjoseToDer: joseToDer\n};\n", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LRUCache = void 0;\nexports.snakeToCamel = snakeToCamel;\nexports.originalOrCamelOptions = originalOrCamelOptions;\nexports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;\nexports.isValidFile = isValidFile;\nexports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json';\nconst CLOUDSDK_CONFIG_DIRECTORY = 'gcloud';\n/**\n * Returns the camel case of a provided string.\n *\n * @remarks\n *\n * Match any `_` and not `_` pair, then return the uppercase of the not `_`\n * character.\n *\n * @param str the string to convert\n * @returns the camelCase'd string\n */\nfunction snakeToCamel(str) {\n return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase());\n}\n/**\n * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference\n * for original, non-camelCase key.\n *\n * @param obj object to lookup a value in\n * @returns a `get` function for getting `obj[key || snakeKey]`, if available\n */\nfunction originalOrCamelOptions(obj) {\n /**\n *\n * @param key an index of object, preferably snake_case\n * @returns the value `obj[key || snakeKey]`, if available\n */\n function get(key) {\n const o = (obj || {});\n return o[key] ?? o[snakeToCamel(key)];\n }\n return { get };\n}\n/**\n * A simple LRU cache utility.\n * Not meant for external usage.\n *\n * @experimental\n */\nclass LRUCache {\n capacity;\n /**\n * Maps are in order. Thus, the older item is the first item.\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}\n */\n #cache = new Map();\n maxAge;\n constructor(options) {\n this.capacity = options.capacity;\n this.maxAge = options.maxAge;\n }\n /**\n * Moves the key to the end of the cache.\n *\n * @param key the key to move\n * @param value the value of the key\n */\n #moveToEnd(key, value) {\n this.#cache.delete(key);\n this.#cache.set(key, {\n value,\n lastAccessed: Date.now(),\n });\n }\n /**\n * Add an item to the cache.\n *\n * @param key the key to upsert\n * @param value the value of the key\n */\n set(key, value) {\n this.#moveToEnd(key, value);\n this.#evict();\n }\n /**\n * Get an item from the cache.\n *\n * @param key the key to retrieve\n */\n get(key) {\n const item = this.#cache.get(key);\n if (!item)\n return;\n this.#moveToEnd(key, item.value);\n this.#evict();\n return item.value;\n }\n /**\n * Maintain the cache based on capacity and TTL.\n */\n #evict() {\n const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;\n /**\n * Because we know Maps are in order, this item is both the\n * last item in the list (capacity) and oldest (maxAge).\n */\n let oldestItem = this.#cache.entries().next();\n while (!oldestItem.done &&\n (this.#cache.size > this.capacity || // too many\n oldestItem.value[1].lastAccessed < cutoffDate) // too old\n ) {\n this.#cache.delete(oldestItem.value[0]);\n oldestItem = this.#cache.entries().next();\n }\n }\n}\nexports.LRUCache = LRUCache;\n// Given and object remove fields where value is undefined.\nfunction removeUndefinedValuesInObject(object) {\n Object.entries(object).forEach(([key, value]) => {\n if (value === undefined || value === 'undefined') {\n delete object[key];\n }\n });\n return object;\n}\n/**\n * Helper to check if a path points to a valid file.\n */\nasync function isValidFile(filePath) {\n try {\n const stats = await fs.promises.lstat(filePath);\n return stats.isFile();\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Determines the well-known gcloud location for the certificate config file.\n * @returns The platform-specific path to the configuration file.\n * @internal\n */\nfunction getWellKnownCertificateConfigFileLocation() {\n const configDir = process.env.CLOUDSDK_CONFIG ||\n (_isWindows()\n ? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY)\n : path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY));\n return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);\n}\n/**\n * Checks if the current operating system is Windows.\n * @returns True if the OS is Windows, false otherwise.\n * @internal\n */\nfunction _isWindows() {\n return os.platform().startsWith('win');\n}\n//# sourceMappingURL=util.js.map", "{\n \"name\": \"google-auth-library\",\n \"version\": \"10.2.0\",\n \"author\": \"Google Inc.\",\n \"description\": \"Google APIs Authentication Client Library for Node.js\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"main\": \"./build/src/index.js\",\n \"types\": \"./build/src/index.d.ts\",\n \"repository\": \"googleapis/google-auth-library-nodejs.git\",\n \"keywords\": [\n \"google\",\n \"api\",\n \"google apis\",\n \"client\",\n \"client library\"\n ],\n \"dependencies\": {\n \"base64-js\": \"^1.3.0\",\n \"ecdsa-sig-formatter\": \"^1.0.11\",\n \"gaxios\": \"^7.0.0\",\n \"gcp-metadata\": \"^7.0.0\",\n \"google-logging-utils\": \"^1.0.0\",\n \"gtoken\": \"^8.0.0\",\n \"jws\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/base64-js\": \"^1.2.5\",\n \"@types/jws\": \"^3.1.0\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"assert-rejects\": \"^1.0.0\",\n \"c8\": \"^10.0.0\",\n \"codecov\": \"^3.0.2\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"keypair\": \"^1.0.4\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.1\",\n \"null-loader\": \"^4.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^21.0.0\",\n \"ts-loader\": \"^8.0.0\",\n \"typescript\": \"^5.1.6\",\n \"webpack\": \"^5.21.2\",\n \"webpack-cli\": \"^4.0.0\"\n },\n \"files\": [\n \"build/src\",\n \"!build/src/**/*.map\"\n ],\n \"scripts\": {\n \"test\": \"c8 mocha build/test\",\n \"clean\": \"gts clean\",\n \"prepare\": \"npm run compile\",\n \"lint\": \"gts check --no-inline-config\",\n \"compile\": \"tsc -p .\",\n \"fix\": \"gts fix\",\n \"pretest\": \"npm run compile -- --sourceMap\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"samples-setup\": \"cd samples/ && npm link ../ && npm run setup && cd ../\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"system-test\": \"mocha build/system-test --timeout 60000\",\n \"presystem-test\": \"npm run compile -- --sourceMap\",\n \"webpack\": \"webpack\",\n \"browser-test\": \"karma start\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"prelint\": \"cd samples; npm link ../; npm install\"\n },\n \"license\": \"Apache-2.0\"\n}\n", "\"use strict\";\n// Copyright 2023 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0;\nconst pkg = require('../../package.json');\nexports.pkg = pkg;\nconst PRODUCT_NAME = 'google-api-nodejs-client';\nexports.PRODUCT_NAME = PRODUCT_NAME;\nconst USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;\nexports.USER_AGENT = USER_AGENT;\n//# sourceMappingURL=shared.cjs.map", "\"use strict\";\n// Copyright 2012 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0;\nconst events_1 = require(\"events\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nconst google_logging_utils_1 = require(\"google-logging-utils\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The default cloud universe\n *\n * @see {@link AuthJSONOptions.universe_domain}\n */\nexports.DEFAULT_UNIVERSE = 'googleapis.com';\n/**\n * The default {@link AuthClientOptions.eagerRefreshThresholdMillis}\n */\nexports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;\n/**\n * The base of all Auth Clients.\n */\nclass AuthClient extends events_1.EventEmitter {\n apiKey;\n projectId;\n /**\n * The quota project ID. The quota project can be used by client libraries for the billing purpose.\n * See {@link https://cloud.google.com/docs/quota Working with quotas}\n */\n quotaProjectId;\n /**\n * The {@link Gaxios `Gaxios`} instance used for making requests.\n */\n transporter;\n credentials = {};\n eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;\n forceRefreshOnFailure = false;\n universeDomain = exports.DEFAULT_UNIVERSE;\n /**\n * Symbols that can be added to GaxiosOptions to specify the method name that is\n * making an RPC call, for logging purposes, as well as a string ID that can be\n * used to correlate calls and responses.\n */\n static RequestMethodNameSymbol = Symbol('request method name');\n static RequestLogIdSymbol = Symbol('request log id');\n constructor(opts = {}) {\n super();\n const options = (0, util_1.originalOrCamelOptions)(opts);\n // Shared auth options\n this.apiKey = opts.apiKey;\n this.projectId = options.get('project_id') ?? null;\n this.quotaProjectId = options.get('quota_project_id');\n this.credentials = options.get('credentials') ?? {};\n this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE;\n // Shared client options\n this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);\n if (options.get('useAuthRequestParameters') !== false) {\n this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR);\n this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);\n }\n if (opts.eagerRefreshThresholdMillis) {\n this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link AuthClient}.\n *\n * @see {@link AuthClient.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const authClient = new AuthClient();\n * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);\n * await fetchWithAuthClient('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n fetch(...args) {\n // Up to 2 parameters in either overload\n const input = args[0];\n const init = args[1];\n let url = undefined;\n const headers = new Headers();\n // prepare URL\n if (typeof input === 'string') {\n url = new URL(input);\n }\n else if (input instanceof URL) {\n url = input;\n }\n else if (input && input.url) {\n url = new URL(input.url);\n }\n // prepare headers\n if (input && typeof input === 'object' && 'headers' in input) {\n gaxios_1.Gaxios.mergeHeaders(headers, input.headers);\n }\n if (init) {\n gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));\n }\n // prepare request\n if (typeof input === 'object' && !(input instanceof URL)) {\n // input must have been a non-URL object\n return this.request({ ...init, ...input, headers, url });\n }\n else {\n // input must have been a string or URL\n return this.request({ ...init, headers, url });\n }\n }\n /**\n * Sets the auth credentials.\n */\n setCredentials(credentials) {\n this.credentials = credentials;\n }\n /**\n * Append additional headers, e.g., x-goog-user-project, shared across the\n * classes inheriting AuthClient. This method should be used by any method\n * that overrides getRequestMetadataAsync(), which is a shared helper for\n * setting request information in both gRPC and HTTP API calls.\n *\n * @param headers object to append additional headers to.\n */\n addSharedMetadataHeaders(headers) {\n // quota_project_id, stored in application_default_credentials.json, is set in\n // the x-goog-user-project header, to indicate an alternate account for\n // billing and quota:\n if (!headers.has('x-goog-user-project') && // don't override a value the user sets.\n this.quotaProjectId) {\n headers.set('x-goog-user-project', this.quotaProjectId);\n }\n return headers;\n }\n /**\n * Adds the `x-goog-user-project` and `authorization` headers to the target Headers\n * object, if they exist on the source.\n *\n * @param target the headers to target\n * @param source the headers to source from\n * @returns the target headers\n */\n addUserProjectAndAuthHeaders(target, source) {\n const xGoogUserProject = source.get('x-goog-user-project');\n const authorizationHeader = source.get('authorization');\n if (xGoogUserProject) {\n target.set('x-goog-user-project', xGoogUserProject);\n }\n if (authorizationHeader) {\n target.set('authorization', authorizationHeader);\n }\n return target;\n }\n static log = (0, google_logging_utils_1.log)('auth');\n static DEFAULT_REQUEST_INTERCEPTOR = {\n resolved: async (config) => {\n // Set `x-goog-api-client`, if not already set\n if (!config.headers.has('x-goog-api-client')) {\n const nodeVersion = process.version.replace(/^v/, '');\n config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`);\n }\n // Set `User-Agent`\n const userAgent = config.headers.get('User-Agent');\n if (!userAgent) {\n config.headers.set('User-Agent', shared_cjs_1.USER_AGENT);\n }\n else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {\n config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`);\n }\n try {\n const symbols = config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n // This doesn't need to be very unique or interesting, it's just an aid for\n // matching requests to responses.\n const logId = `${Math.floor(Math.random() * 1000)}`;\n symbols[AuthClient.RequestLogIdSymbol] = logId;\n // Boil down the object we're printing out.\n const logObject = {\n url: config.url,\n headers: config.headers,\n };\n if (methodName) {\n AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject);\n }\n else {\n AuthClient.log.info('[%s] request %j', logId, logObject);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return config;\n },\n };\n static DEFAULT_RESPONSE_INTERCEPTOR = {\n resolved: async (response) => {\n try {\n const symbols = response.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data);\n }\n else {\n AuthClient.log.info('[%s] response %j', logId, response.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return response;\n },\n rejected: async (error) => {\n try {\n const symbols = error.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data);\n }\n else {\n AuthClient.log.error('[%s] error %j', logId, error.response?.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n // Re-throw the error.\n throw error;\n },\n };\n /**\n * Sets the method name that is making a Gaxios request, so that logging may tag\n * log lines with the operation.\n * @param config A Gaxios request config\n * @param methodName The method name making the call\n */\n static setMethodName(config, methodName) {\n try {\n const symbols = config;\n symbols[AuthClient.RequestMethodNameSymbol] = methodName;\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.AuthClient = AuthClient;\n//# sourceMappingURL=authclient.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LoginTicket = void 0;\nclass LoginTicket {\n envelope;\n payload;\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @param {string} env Envelope of the jwt\n * @param {TokenPayload} pay Payload of the jwt\n * @constructor\n */\n constructor(env, pay) {\n this.envelope = env;\n this.payload = pay;\n }\n getEnvelope() {\n return this.envelope;\n }\n getPayload() {\n return this.payload;\n }\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @return The user ID\n */\n getUserId() {\n const payload = this.getPayload();\n if (payload && payload.sub) {\n return payload.sub;\n }\n return null;\n }\n /**\n * Returns attributes from the login ticket. This can contain\n * various information about the user session.\n *\n * @return The envelope and payload\n */\n getAttributes() {\n return { envelope: this.getEnvelope(), payload: this.getPayload() };\n }\n}\nexports.LoginTicket = LoginTicket;\n//# sourceMappingURL=loginticket.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst querystring = require(\"querystring\");\nconst stream = require(\"stream\");\nconst formatEcdsa = require(\"ecdsa-sig-formatter\");\nconst util_1 = require(\"../util\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst authclient_1 = require(\"./authclient\");\nconst loginticket_1 = require(\"./loginticket\");\nvar CodeChallengeMethod;\n(function (CodeChallengeMethod) {\n CodeChallengeMethod[\"Plain\"] = \"plain\";\n CodeChallengeMethod[\"S256\"] = \"S256\";\n})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {}));\nvar CertificateFormat;\n(function (CertificateFormat) {\n CertificateFormat[\"PEM\"] = \"PEM\";\n CertificateFormat[\"JWK\"] = \"JWK\";\n})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {}));\n/**\n * The client authentication type. Supported values are basic, post, and none.\n * https://datatracker.ietf.org/doc/html/rfc7591#section-2\n */\nvar ClientAuthentication;\n(function (ClientAuthentication) {\n ClientAuthentication[\"ClientSecretPost\"] = \"ClientSecretPost\";\n ClientAuthentication[\"ClientSecretBasic\"] = \"ClientSecretBasic\";\n ClientAuthentication[\"None\"] = \"None\";\n})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {}));\nclass OAuth2Client extends authclient_1.AuthClient {\n redirectUri;\n certificateCache = {};\n certificateExpiry = null;\n certificateCacheFormat = CertificateFormat.PEM;\n refreshTokenPromises = new Map();\n endpoints;\n issuers;\n clientAuthentication;\n // TODO: refactor tests to make this private\n _clientId;\n // TODO: refactor tests to make this private\n _clientSecret;\n refreshHandler;\n /**\n * An OAuth2 Client for Google APIs.\n *\n * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n */\n constructor(options = {}, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n redirectUri) {\n super(typeof options === 'object' ? options : {});\n if (typeof options !== 'object') {\n options = {\n clientId: options,\n clientSecret,\n redirectUri,\n };\n }\n this._clientId = options.clientId || options.client_id;\n this._clientSecret = options.clientSecret || options.client_secret;\n this.redirectUri = options.redirectUri || options.redirect_uris?.[0];\n this.endpoints = {\n tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo',\n oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n oauth2TokenUrl: 'https://oauth2.googleapis.com/token',\n oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke',\n oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs',\n oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs',\n oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key',\n ...options.endpoints,\n };\n this.clientAuthentication =\n options.clientAuthentication || ClientAuthentication.ClientSecretPost;\n this.issuers = options.issuers || [\n 'accounts.google.com',\n 'https://accounts.google.com',\n this.universeDomain,\n ];\n }\n /**\n * @deprecated use instance's {@link OAuth2Client.endpoints}\n */\n static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';\n /**\n * Clock skew - five minutes in seconds\n */\n static CLOCK_SKEW_SECS_ = 300;\n /**\n * The default max Token Lifetime is one day in seconds\n */\n static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;\n /**\n * Generates URL for consent page landing.\n * @param opts Options.\n * @return URL to consent page.\n */\n generateAuthUrl(opts = {}) {\n if (opts.code_challenge_method && !opts.code_challenge) {\n throw new Error('If a code_challenge_method is provided, code_challenge must be included.');\n }\n opts.response_type = opts.response_type || 'code';\n opts.client_id = opts.client_id || this._clientId;\n opts.redirect_uri = opts.redirect_uri || this.redirectUri;\n // Allow scopes to be passed either as array or a string\n if (Array.isArray(opts.scope)) {\n opts.scope = opts.scope.join(' ');\n }\n const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();\n return (rootUrl +\n '?' +\n querystring.stringify(opts));\n }\n generateCodeVerifier() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');\n }\n /**\n * Convenience method to automatically generate a code_verifier, and its\n * resulting SHA256. If used, this must be paired with a S256\n * code_challenge_method.\n *\n * For a full example see:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js\n */\n async generateCodeVerifierAsync() {\n // base64 encoding uses 6 bits per character, and we want to generate128\n // characters. 6*128/8 = 96.\n const crypto = (0, crypto_1.createCrypto)();\n const randomString = crypto.randomBytesBase64(96);\n // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/\n // \"-\"/\".\"/\"_\"/\"~\". Base64 encoded strings are pretty close, so we're just\n // swapping out a few chars.\n const codeVerifier = randomString\n .replace(/\\+/g, '~')\n .replace(/=/g, '_')\n .replace(/\\//g, '-');\n // Generate the base64 encoded SHA256\n const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);\n // We need to use base64UrlEncoding instead of standard base64\n const codeChallenge = unencodedCodeChallenge\n .split('=')[0]\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n return { codeVerifier, codeChallenge };\n }\n getToken(codeOrOptions, callback) {\n const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;\n if (callback) {\n this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));\n }\n else {\n return this.getTokenAsync(options);\n }\n }\n async getTokenAsync(options) {\n const url = this.endpoints.oauth2TokenUrl.toString();\n const headers = new Headers();\n const values = {\n client_id: options.client_id || this._clientId,\n code_verifier: options.codeVerifier,\n code: options.code,\n grant_type: 'authorization_code',\n redirect_uri: options.redirect_uri || this.redirectUri,\n };\n if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {\n const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);\n headers.set('authorization', `Basic ${basic.toString('base64')}`);\n }\n if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {\n values.client_secret = this._clientSecret;\n }\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync');\n const res = await this.transporter.request(opts);\n const tokens = res.data;\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n /**\n * Refreshes the access token.\n * @param refresh_token Existing refresh token.\n * @private\n */\n async refreshToken(refreshToken) {\n if (!refreshToken) {\n return this.refreshTokenNoCache(refreshToken);\n }\n // If a request to refresh using the same token has started,\n // return the same promise.\n if (this.refreshTokenPromises.has(refreshToken)) {\n return this.refreshTokenPromises.get(refreshToken);\n }\n const p = this.refreshTokenNoCache(refreshToken).then(r => {\n this.refreshTokenPromises.delete(refreshToken);\n return r;\n }, e => {\n this.refreshTokenPromises.delete(refreshToken);\n throw e;\n });\n this.refreshTokenPromises.set(refreshToken, p);\n return p;\n }\n async refreshTokenNoCache(refreshToken) {\n if (!refreshToken) {\n throw new Error('No refresh token is set.');\n }\n const url = this.endpoints.oauth2TokenUrl.toString();\n const data = {\n refresh_token: refreshToken,\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n };\n let res;\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache');\n // request for new token\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError &&\n e.message === 'invalid_grant' &&\n e.response?.data &&\n /ReAuth/i.test(e.response.data.error_description)) {\n e.message = JSON.stringify(e.response.data);\n }\n throw e;\n }\n const tokens = res.data;\n // TODO: de-duplicate this code from a few spots\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n refreshAccessToken(callback) {\n if (callback) {\n this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);\n }\n else {\n return this.refreshAccessTokenAsync();\n }\n }\n async refreshAccessTokenAsync() {\n const r = await this.refreshToken(this.credentials.refresh_token);\n const tokens = r.tokens;\n tokens.refresh_token = this.credentials.refresh_token;\n this.credentials = tokens;\n return { credentials: this.credentials, res: r.res };\n }\n getAccessToken(callback) {\n if (callback) {\n this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);\n }\n else {\n return this.getAccessTokenAsync();\n }\n }\n async getAccessTokenAsync() {\n const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();\n if (shouldRefresh) {\n if (!this.credentials.refresh_token) {\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n return { token: this.credentials.access_token };\n }\n }\n else {\n throw new Error('No refresh token or refresh handler callback is set.');\n }\n }\n const r = await this.refreshAccessTokenAsync();\n if (!r.credentials || (r.credentials && !r.credentials.access_token)) {\n throw new Error('Could not refresh access token.');\n }\n return { token: r.credentials.access_token, res: r.res };\n }\n else {\n return { token: this.credentials.access_token };\n }\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * In OAuth2Client, the result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders(url) {\n const headers = (await this.getRequestMetadataAsync(url)).headers;\n return headers;\n }\n async getRequestMetadataAsync(url) {\n url;\n const thisCreds = this.credentials;\n if (!thisCreds.access_token &&\n !thisCreds.refresh_token &&\n !this.apiKey &&\n !this.refreshHandler) {\n throw new Error('No access, refresh token, API key or refresh handler callback is set.');\n }\n if (thisCreds.access_token && !this.isTokenExpiring()) {\n thisCreds.token_type = thisCreds.token_type || 'Bearer';\n const headers = new Headers({\n authorization: thisCreds.token_type + ' ' + thisCreds.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n // If refreshHandler exists, call processAndValidateRefreshHandler().\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n if (this.apiKey) {\n return { headers: new Headers({ 'X-Goog-Api-Key': this.apiKey }) };\n }\n let r = null;\n let tokens = null;\n try {\n r = await this.refreshToken(thisCreds.refresh_token);\n tokens = r.tokens;\n }\n catch (err) {\n const e = err;\n if (e.response &&\n (e.response.status === 403 || e.response.status === 404)) {\n e.message = `Could not refresh access token: ${e.message}`;\n }\n throw e;\n }\n const credentials = this.credentials;\n credentials.token_type = credentials.token_type || 'Bearer';\n tokens.refresh_token = credentials.refresh_token;\n this.credentials = tokens;\n const headers = new Headers({\n authorization: credentials.token_type + ' ' + tokens.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers), res: r.res };\n }\n /**\n * Generates an URL to revoke the given token.\n * @param token The existing token to be revoked.\n *\n * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}\n */\n static getRevokeTokenUrl(token) {\n return new OAuth2Client().getRevokeTokenURL(token).toString();\n }\n /**\n * Generates a URL to revoke the given token.\n *\n * @param token The existing token to be revoked.\n */\n getRevokeTokenURL(token) {\n const url = new URL(this.endpoints.oauth2RevokeUrl);\n url.searchParams.append('token', token);\n return url;\n }\n revokeToken(token, callback) {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url: this.getRevokeTokenURL(token).toString(),\n method: 'POST',\n };\n authclient_1.AuthClient.setMethodName(opts, 'revokeToken');\n if (callback) {\n this.transporter\n .request(opts)\n .then(r => callback(null, r), callback);\n }\n else {\n return this.transporter.request(opts);\n }\n }\n revokeCredentials(callback) {\n if (callback) {\n this.revokeCredentialsAsync().then(res => callback(null, res), callback);\n }\n else {\n return this.revokeCredentialsAsync();\n }\n }\n async revokeCredentialsAsync() {\n const token = this.credentials.access_token;\n this.credentials = {};\n if (token) {\n return this.revokeToken(token);\n }\n else {\n throw new Error('No access token to revoke.');\n }\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n async requestAsync(opts, reAuthRetried = false) {\n try {\n const r = await this.getRequestMetadataAsync();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, r.headers);\n if (this.apiKey) {\n opts.headers.set('X-Goog-Api-Key', this.apiKey);\n }\n return await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - An access_token and refresh_token were available, but either no\n // expiry_date was available or the forceRefreshOnFailure flag is set.\n // The absent expiry_date case can happen when developers stash the\n // access_token and refresh_token for later use, but the access_token\n // fails on the first try because it's expired. Some developers may\n // choose to enable forceRefreshOnFailure to mitigate time-related\n // errors.\n // Or the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - No refresh_token was available\n // - An access_token and a refreshHandler callback were available, but\n // either no expiry_date was available or the forceRefreshOnFailure\n // flag is set. The access_token fails on the first try because it's\n // expired. Some developers may choose to enable forceRefreshOnFailure\n // to mitigate time-related errors.\n const mayRequireRefresh = this.credentials &&\n this.credentials.access_token &&\n this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure);\n const mayRequireRefreshWithNoRefreshToken = this.credentials &&\n this.credentials.access_token &&\n !this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&\n this.refreshHandler;\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefresh) {\n await this.refreshAccessTokenAsync();\n return this.requestAsync(opts, true);\n }\n else if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefreshWithNoRefreshToken) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n }\n return this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n }\n verifyIdToken(options, callback) {\n // This function used to accept two arguments instead of an options object.\n // Check the types to help users upgrade with less pain.\n // This check can be removed after a 2.0 release.\n if (callback && typeof callback !== 'function') {\n throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');\n }\n if (callback) {\n this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);\n }\n else {\n return this.verifyIdTokenAsync(options);\n }\n }\n async verifyIdTokenAsync(options) {\n if (!options.idToken) {\n throw new Error('The verifyIdToken method requires an ID Token');\n }\n const response = await this.getFederatedSignonCertsAsync();\n const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry);\n return login;\n }\n /**\n * Obtains information about the provisioned access token. Especially useful\n * if you want to check the scopes that were provisioned to a given token.\n *\n * @param accessToken Required. The Access Token for which you want to get\n * user info.\n */\n async getTokenInfo(accessToken) {\n const { data } = await this.transporter.request({\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',\n authorization: `Bearer ${accessToken}`,\n },\n url: this.endpoints.tokenInfoUrl.toString(),\n });\n const info = Object.assign({\n expiry_date: new Date().getTime() + data.expires_in * 1000,\n scopes: data.scope.split(' '),\n }, data);\n delete info.expires_in;\n delete info.scope;\n return info;\n }\n getFederatedSignonCerts(callback) {\n if (callback) {\n this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);\n }\n else {\n return this.getFederatedSignonCertsAsync();\n }\n }\n async getFederatedSignonCertsAsync() {\n const nowTime = new Date().getTime();\n const format = (0, crypto_1.hasBrowserCrypto)()\n ? CertificateFormat.JWK\n : CertificateFormat.PEM;\n if (this.certificateExpiry &&\n nowTime < this.certificateExpiry.getTime() &&\n this.certificateCacheFormat === format) {\n return { certs: this.certificateCache, format };\n }\n let res;\n let url;\n switch (format) {\n case CertificateFormat.PEM:\n url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();\n break;\n case CertificateFormat.JWK:\n url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n const cacheControl = res?.headers.get('cache-control');\n let cacheAge = -1;\n if (cacheControl) {\n const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups\n ?.maxAge;\n if (maxAge) {\n // Cache results with max-age (in seconds)\n cacheAge = Number(maxAge) * 1000; // milliseconds\n }\n }\n let certificates = {};\n switch (format) {\n case CertificateFormat.PEM:\n certificates = res.data;\n break;\n case CertificateFormat.JWK:\n for (const key of res.data.keys) {\n certificates[key.kid] = key;\n }\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n const now = new Date();\n this.certificateExpiry =\n cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);\n this.certificateCache = certificates;\n this.certificateCacheFormat = format;\n return { certs: certificates, format, res };\n }\n getIapPublicKeys(callback) {\n if (callback) {\n this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);\n }\n else {\n return this.getIapPublicKeysAsync();\n }\n }\n async getIapPublicKeysAsync() {\n let res;\n const url = this.endpoints.oauth2IapPublicKeyUrl.toString();\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n return { pubkeys: res.data, res };\n }\n verifySignedJwtWithCerts() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');\n }\n /**\n * Verify the id token is signed with the correct certificate\n * and is from the correct audience.\n * @param jwt The jwt to verify (The ID Token in this case).\n * @param certs The array of certs to test the jwt against.\n * @param requiredAudience The audience to test the jwt against.\n * @param issuers The allowed issuers of the jwt (Optional).\n * @param maxExpiry The max expiry the certificate can be (Optional).\n * @return Returns a promise resolving to LoginTicket on verification.\n */\n async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {\n const crypto = (0, crypto_1.createCrypto)();\n if (!maxExpiry) {\n maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;\n }\n const segments = jwt.split('.');\n if (segments.length !== 3) {\n throw new Error('Wrong number of segments in token: ' + jwt);\n }\n const signed = segments[0] + '.' + segments[1];\n let signature = segments[2];\n let envelope;\n let payload;\n try {\n envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;\n }\n throw err;\n }\n if (!envelope) {\n throw new Error(\"Can't parse token envelope: \" + segments[0]);\n }\n try {\n payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token payload '${segments[0]}`;\n }\n throw err;\n }\n if (!payload) {\n throw new Error(\"Can't parse token payload: \" + segments[1]);\n }\n if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {\n // If this is not present, then there's no reason to attempt verification\n throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));\n }\n const cert = certs[envelope.kid];\n if (envelope.alg === 'ES256') {\n signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');\n }\n const verified = await crypto.verify(cert, signed, signature);\n if (!verified) {\n throw new Error('Invalid token signature: ' + jwt);\n }\n if (!payload.iat) {\n throw new Error('No issue time in token: ' + JSON.stringify(payload));\n }\n if (!payload.exp) {\n throw new Error('No expiration time in token: ' + JSON.stringify(payload));\n }\n const iat = Number(payload.iat);\n if (isNaN(iat))\n throw new Error('iat field using invalid format');\n const exp = Number(payload.exp);\n if (isNaN(exp))\n throw new Error('exp field using invalid format');\n const now = new Date().getTime() / 1000;\n if (exp >= now + maxExpiry) {\n throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));\n }\n const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;\n const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;\n if (now < earliest) {\n throw new Error('Token used too early, ' +\n now +\n ' < ' +\n earliest +\n ': ' +\n JSON.stringify(payload));\n }\n if (now > latest) {\n throw new Error('Token used too late, ' +\n now +\n ' > ' +\n latest +\n ': ' +\n JSON.stringify(payload));\n }\n if (issuers && issuers.indexOf(payload.iss) < 0) {\n throw new Error('Invalid issuer, expected one of [' +\n issuers +\n '], but got ' +\n payload.iss);\n }\n // Check the audience matches if we have one\n if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {\n const aud = payload.aud;\n let audVerified = false;\n // If the requiredAudience is an array, check if it contains token\n // audience\n if (requiredAudience.constructor === Array) {\n audVerified = requiredAudience.indexOf(aud) > -1;\n }\n else {\n audVerified = aud === requiredAudience;\n }\n if (!audVerified) {\n throw new Error('Wrong recipient, payload audience != requiredAudience');\n }\n }\n return new loginticket_1.LoginTicket(envelope, payload);\n }\n /**\n * Returns a promise that resolves with AccessTokenResponse type if\n * refreshHandler is defined.\n * If not, nothing is returned.\n */\n async processAndValidateRefreshHandler() {\n if (this.refreshHandler) {\n const accessTokenResponse = await this.refreshHandler();\n if (!accessTokenResponse.access_token) {\n throw new Error('No access token is returned by the refreshHandler callback.');\n }\n return accessTokenResponse;\n }\n return;\n }\n /**\n * Returns true if a token is expired or will expire within\n * eagerRefreshThresholdMillismilliseconds.\n * If there is no expiry time, assumes the token is not expired or expiring.\n */\n isTokenExpiring() {\n const expiryDate = this.credentials.expiry_date;\n return expiryDate\n ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.OAuth2Client = OAuth2Client;\n//# sourceMappingURL=oauth2client.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Compute = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst oauth2client_1 = require(\"./oauth2client\");\nclass Compute extends oauth2client_1.OAuth2Client {\n serviceAccountEmail;\n scopes;\n /**\n * Google Compute Engine service account credentials.\n *\n * Retrieve access token from the metadata server.\n * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };\n this.serviceAccountEmail = options.serviceAccountEmail || 'default';\n this.scopes = Array.isArray(options.scopes)\n ? options.scopes\n : options.scopes\n ? [options.scopes]\n : [];\n }\n /**\n * Refreshes the access token.\n * @param refreshToken Unused parameter\n */\n async refreshTokenNoCache() {\n const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;\n let data;\n try {\n const instanceOptions = {\n property: tokenPath,\n };\n if (this.scopes.length > 0) {\n instanceOptions.params = {\n scopes: this.scopes.join(','),\n };\n }\n data = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError) {\n e.message = `Could not refresh access token: ${e.message}`;\n this.wrapError(e);\n }\n throw e;\n }\n const tokens = data;\n if (data && data.expires_in) {\n tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res: null };\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +\n `?format=full&audience=${targetAudience}`;\n let idToken;\n try {\n const instanceOptions = {\n property: idTokenPath,\n };\n idToken = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Could not fetch ID token: ${e.message}`;\n }\n throw e;\n }\n return idToken;\n }\n wrapError(e) {\n const res = e.response;\n if (res && res.status) {\n e.status = res.status;\n if (res.status === 403) {\n e.message =\n 'A Forbidden error was returned while attempting to retrieve an access ' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have the correct permission scopes specified: ' +\n e.message;\n }\n else if (res.status === 404) {\n e.message =\n 'A Not Found error was returned while attempting to retrieve an access' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have any permission scopes specified: ' +\n e.message;\n }\n }\n }\n}\nexports.Compute = Compute;\n//# sourceMappingURL=computeclient.js.map", "\"use strict\";\n// Copyright 2020 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdTokenClient = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nclass IdTokenClient extends oauth2client_1.OAuth2Client {\n targetAudience;\n idTokenProvider;\n /**\n * Google ID Token client\n *\n * Retrieve ID token from the metadata server.\n * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server\n */\n constructor(options) {\n super(options);\n this.targetAudience = options.targetAudience;\n this.idTokenProvider = options.idTokenProvider;\n }\n async getRequestMetadataAsync() {\n if (!this.credentials.id_token ||\n !this.credentials.expiry_date ||\n this.isTokenExpiring()) {\n const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);\n this.credentials = {\n id_token: idToken,\n expiry_date: this.getIdTokenExpiryDate(idToken),\n };\n }\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.id_token,\n });\n return { headers };\n }\n getIdTokenExpiryDate(idToken) {\n const payloadB64 = idToken.split('.')[1];\n if (payloadB64) {\n const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));\n return payload.exp * 1000;\n }\n }\n}\nexports.IdTokenClient = IdTokenClient;\n//# sourceMappingURL=idtokenclient.js.map", "\"use strict\";\n// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GCPEnv = void 0;\nexports.clear = clear;\nexports.getEnv = getEnv;\nconst gcpMetadata = require(\"gcp-metadata\");\nvar GCPEnv;\n(function (GCPEnv) {\n GCPEnv[\"APP_ENGINE\"] = \"APP_ENGINE\";\n GCPEnv[\"KUBERNETES_ENGINE\"] = \"KUBERNETES_ENGINE\";\n GCPEnv[\"CLOUD_FUNCTIONS\"] = \"CLOUD_FUNCTIONS\";\n GCPEnv[\"COMPUTE_ENGINE\"] = \"COMPUTE_ENGINE\";\n GCPEnv[\"CLOUD_RUN\"] = \"CLOUD_RUN\";\n GCPEnv[\"NONE\"] = \"NONE\";\n})(GCPEnv || (exports.GCPEnv = GCPEnv = {}));\nlet envPromise;\nfunction clear() {\n envPromise = undefined;\n}\nasync function getEnv() {\n if (envPromise) {\n return envPromise;\n }\n envPromise = getEnvMemoized();\n return envPromise;\n}\nasync function getEnvMemoized() {\n let env = GCPEnv.NONE;\n if (isAppEngine()) {\n env = GCPEnv.APP_ENGINE;\n }\n else if (isCloudFunction()) {\n env = GCPEnv.CLOUD_FUNCTIONS;\n }\n else if (await isComputeEngine()) {\n if (await isKubernetesEngine()) {\n env = GCPEnv.KUBERNETES_ENGINE;\n }\n else if (isCloudRun()) {\n env = GCPEnv.CLOUD_RUN;\n }\n else {\n env = GCPEnv.COMPUTE_ENGINE;\n }\n }\n else {\n env = GCPEnv.NONE;\n }\n return env;\n}\nfunction isAppEngine() {\n return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);\n}\nfunction isCloudFunction() {\n return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);\n}\n/**\n * This check only verifies that the environment is running knative.\n * This must be run *after* checking for Kubernetes, otherwise it will\n * return a false positive.\n */\nfunction isCloudRun() {\n return !!process.env.K_CONFIGURATION;\n}\nasync function isKubernetesEngine() {\n try {\n await gcpMetadata.instance('attributes/cluster-name');\n return true;\n }\n catch (e) {\n return false;\n }\n}\nasync function isComputeEngine() {\n return gcpMetadata.isAvailable();\n}\n//# sourceMappingURL=envDetect.js.map", "/*global module, process*/\nvar Buffer = require('safe-buffer').Buffer;\nvar Stream = require('stream');\nvar util = require('util');\n\nfunction DataStream(data) {\n this.buffer = null;\n this.writable = true;\n this.readable = true;\n\n // No input\n if (!data) {\n this.buffer = Buffer.alloc(0);\n return this;\n }\n\n // Stream\n if (typeof data.pipe === 'function') {\n this.buffer = Buffer.alloc(0);\n data.pipe(this);\n return this;\n }\n\n // Buffer or String\n // or Object (assumedly a passworded key)\n if (data.length || typeof data === 'object') {\n this.buffer = data;\n this.writable = false;\n process.nextTick(function () {\n this.emit('end', data);\n this.readable = false;\n this.emit('close');\n }.bind(this));\n return this;\n }\n\n throw new TypeError('Unexpected data type ('+ typeof data + ')');\n}\nutil.inherits(DataStream, Stream);\n\nDataStream.prototype.write = function write(data) {\n this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);\n this.emit('data', data);\n};\n\nDataStream.prototype.end = function end(data) {\n if (data)\n this.write(data);\n this.emit('end', data);\n this.emit('close');\n this.writable = false;\n this.readable = false;\n};\n\nmodule.exports = DataStream;\n", "/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n", "var Buffer = require('safe-buffer').Buffer;\nvar crypto = require('crypto');\nvar formatEcdsa = require('ecdsa-sig-formatter');\nvar util = require('util');\n\nvar MSG_INVALID_ALGORITHM = '\"%s\" is not a valid algorithm.\\n Supported algorithms are:\\n \"HS256\", \"HS384\", \"HS512\", \"RS256\", \"RS384\", \"RS512\", \"PS256\", \"PS384\", \"PS512\", \"ES256\", \"ES384\", \"ES512\" and \"none\".'\nvar MSG_INVALID_SECRET = 'secret must be a string or buffer';\nvar MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';\nvar MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';\n\nvar supportsKeyObjects = typeof crypto.createPublicKey === 'function';\nif (supportsKeyObjects) {\n MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';\n MSG_INVALID_SECRET += 'or a KeyObject';\n}\n\nfunction checkIsPublicKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.type !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.asymmetricKeyType !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n};\n\nfunction checkIsPrivateKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (typeof key === 'object') {\n return;\n }\n\n throw typeError(MSG_INVALID_SIGNER_KEY);\n};\n\nfunction checkIsSecretKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (key.type !== 'secret') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_SECRET);\n }\n}\n\nfunction fromBase64(base64) {\n return base64\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction toBase64(base64url) {\n base64url = base64url.toString();\n\n var padding = 4 - base64url.length % 4;\n if (padding !== 4) {\n for (var i = 0; i < padding; ++i) {\n base64url += '=';\n }\n }\n\n return base64url\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n}\n\nfunction typeError(template) {\n var args = [].slice.call(arguments, 1);\n var errMsg = util.format.bind(util, template).apply(null, args);\n return new TypeError(errMsg);\n}\n\nfunction bufferOrString(obj) {\n return Buffer.isBuffer(obj) || typeof obj === 'string';\n}\n\nfunction normalizeInput(thing) {\n if (!bufferOrString(thing))\n thing = JSON.stringify(thing);\n return thing;\n}\n\nfunction createHmacSigner(bits) {\n return function sign(thing, secret) {\n checkIsSecretKey(secret);\n thing = normalizeInput(thing);\n var hmac = crypto.createHmac('sha' + bits, secret);\n var sig = (hmac.update(thing), hmac.digest('base64'))\n return fromBase64(sig);\n }\n}\n\nvar bufferEqual;\nvar timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n return crypto.timingSafeEqual(a, b)\n} : function timingSafeEqual(a, b) {\n if (!bufferEqual) {\n bufferEqual = require('buffer-equal-constant-time');\n }\n\n return bufferEqual(a, b)\n}\n\nfunction createHmacVerifier(bits) {\n return function verify(thing, signature, secret) {\n var computedSig = createHmacSigner(bits)(thing, secret);\n return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));\n }\n}\n\nfunction createKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n // Even though we are specifying \"RSA\" here, this works with ECDSA\n // keys as well.\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify(publicKey, signature, 'base64');\n }\n}\n\nfunction createPSSKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign({\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createPSSKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify({\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, signature, 'base64');\n }\n}\n\nfunction createECDSASigner(bits) {\n var inner = createKeySigner(bits);\n return function sign() {\n var signature = inner.apply(null, arguments);\n signature = formatEcdsa.derToJose(signature, 'ES' + bits);\n return signature;\n };\n}\n\nfunction createECDSAVerifer(bits) {\n var inner = createKeyVerifier(bits);\n return function verify(thing, signature, publicKey) {\n signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');\n var result = inner(thing, signature, publicKey);\n return result;\n };\n}\n\nfunction createNoneSigner() {\n return function sign() {\n return '';\n }\n}\n\nfunction createNoneVerifier() {\n return function verify(thing, signature) {\n return signature === '';\n }\n}\n\nmodule.exports = function jwa(algorithm) {\n var signerFactories = {\n hs: createHmacSigner,\n rs: createKeySigner,\n ps: createPSSKeySigner,\n es: createECDSASigner,\n none: createNoneSigner,\n }\n var verifierFactories = {\n hs: createHmacVerifier,\n rs: createKeyVerifier,\n ps: createPSSKeyVerifier,\n es: createECDSAVerifer,\n none: createNoneVerifier,\n }\n var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);\n if (!match)\n throw typeError(MSG_INVALID_ALGORITHM, algorithm);\n var algo = (match[1] || match[3]).toLowerCase();\n var bits = match[2];\n\n return {\n sign: signerFactories[algo](bits),\n verify: verifierFactories[algo](bits),\n }\n};\n", "/*global module*/\nvar Buffer = require('buffer').Buffer;\n\nmodule.exports = function toString(obj) {\n if (typeof obj === 'string')\n return obj;\n if (typeof obj === 'number' || Buffer.isBuffer(obj))\n return obj.toString();\n return JSON.stringify(obj);\n};\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\n\nfunction base64url(string, encoding) {\n return Buffer\n .from(string, encoding)\n .toString('base64')\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction jwsSecuredInput(header, payload, encoding) {\n encoding = encoding || 'utf8';\n var encodedHeader = base64url(toString(header), 'binary');\n var encodedPayload = base64url(toString(payload), encoding);\n return util.format('%s.%s', encodedHeader, encodedPayload);\n}\n\nfunction jwsSign(opts) {\n var header = opts.header;\n var payload = opts.payload;\n var secretOrKey = opts.secret || opts.privateKey;\n var encoding = opts.encoding;\n var algo = jwa(header.alg);\n var securedInput = jwsSecuredInput(header, payload, encoding);\n var signature = algo.sign(securedInput, secretOrKey);\n return util.format('%s.%s', securedInput, signature);\n}\n\nfunction SignStream(opts) {\n var secret = opts.secret||opts.privateKey||opts.key;\n var secretStream = new DataStream(secret);\n this.readable = true;\n this.header = opts.header;\n this.encoding = opts.encoding;\n this.secret = this.privateKey = this.key = secretStream;\n this.payload = new DataStream(opts.payload);\n this.secret.once('close', function () {\n if (!this.payload.writable && this.readable)\n this.sign();\n }.bind(this));\n\n this.payload.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.sign();\n }.bind(this));\n}\nutil.inherits(SignStream, Stream);\n\nSignStream.prototype.sign = function sign() {\n try {\n var signature = jwsSign({\n header: this.header,\n payload: this.payload.buffer,\n secret: this.secret.buffer,\n encoding: this.encoding\n });\n this.emit('done', signature);\n this.emit('data', signature);\n this.emit('end');\n this.readable = false;\n return signature;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nSignStream.sign = jwsSign;\n\nmodule.exports = SignStream;\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\nvar JWS_REGEX = /^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?$/;\n\nfunction isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}\n\nfunction safeJsonParse(thing) {\n if (isObject(thing))\n return thing;\n try { return JSON.parse(thing); }\n catch (e) { return undefined; }\n}\n\nfunction headerFromJWS(jwsSig) {\n var encodedHeader = jwsSig.split('.', 1)[0];\n return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));\n}\n\nfunction securedInputFromJWS(jwsSig) {\n return jwsSig.split('.', 2).join('.');\n}\n\nfunction signatureFromJWS(jwsSig) {\n return jwsSig.split('.')[2];\n}\n\nfunction payloadFromJWS(jwsSig, encoding) {\n encoding = encoding || 'utf8';\n var payload = jwsSig.split('.')[1];\n return Buffer.from(payload, 'base64').toString(encoding);\n}\n\nfunction isValidJws(string) {\n return JWS_REGEX.test(string) && !!headerFromJWS(string);\n}\n\nfunction jwsVerify(jwsSig, algorithm, secretOrKey) {\n if (!algorithm) {\n var err = new Error(\"Missing algorithm parameter for jws.verify\");\n err.code = \"MISSING_ALGORITHM\";\n throw err;\n }\n jwsSig = toString(jwsSig);\n var signature = signatureFromJWS(jwsSig);\n var securedInput = securedInputFromJWS(jwsSig);\n var algo = jwa(algorithm);\n return algo.verify(securedInput, signature, secretOrKey);\n}\n\nfunction jwsDecode(jwsSig, opts) {\n opts = opts || {};\n jwsSig = toString(jwsSig);\n\n if (!isValidJws(jwsSig))\n return null;\n\n var header = headerFromJWS(jwsSig);\n\n if (!header)\n return null;\n\n var payload = payloadFromJWS(jwsSig);\n if (header.typ === 'JWT' || opts.json)\n payload = JSON.parse(payload, opts.encoding);\n\n return {\n header: header,\n payload: payload,\n signature: signatureFromJWS(jwsSig)\n };\n}\n\nfunction VerifyStream(opts) {\n opts = opts || {};\n var secretOrKey = opts.secret||opts.publicKey||opts.key;\n var secretStream = new DataStream(secretOrKey);\n this.readable = true;\n this.algorithm = opts.algorithm;\n this.encoding = opts.encoding;\n this.secret = this.publicKey = this.key = secretStream;\n this.signature = new DataStream(opts.signature);\n this.secret.once('close', function () {\n if (!this.signature.writable && this.readable)\n this.verify();\n }.bind(this));\n\n this.signature.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.verify();\n }.bind(this));\n}\nutil.inherits(VerifyStream, Stream);\nVerifyStream.prototype.verify = function verify() {\n try {\n var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);\n var obj = jwsDecode(this.signature.buffer, this.encoding);\n this.emit('done', valid, obj);\n this.emit('data', valid);\n this.emit('end');\n this.readable = false;\n return valid;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nVerifyStream.decode = jwsDecode;\nVerifyStream.isValid = isValidJws;\nVerifyStream.verify = jwsVerify;\n\nmodule.exports = VerifyStream;\n", "/*global exports*/\nvar SignStream = require('./lib/sign-stream');\nvar VerifyStream = require('./lib/verify-stream');\n\nvar ALGORITHMS = [\n 'HS256', 'HS384', 'HS512',\n 'RS256', 'RS384', 'RS512',\n 'PS256', 'PS384', 'PS512',\n 'ES256', 'ES384', 'ES512'\n];\n\nexports.ALGORITHMS = ALGORITHMS;\nexports.sign = SignStream.sign;\nexports.verify = VerifyStream.verify;\nexports.decode = VerifyStream.decode;\nexports.isValid = VerifyStream.isValid;\nexports.createSign = function createSign(opts) {\n return new SignStream(opts);\n};\nexports.createVerify = function createVerify(opts) {\n return new VerifyStream(opts);\n};\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.GoogleToken = void 0;\nvar fs = _interopRequireWildcard(require(\"fs\"));\nvar _gaxios = require(\"gaxios\");\nvar jws = _interopRequireWildcard(require(\"jws\"));\nvar path = _interopRequireWildcard(require(\"path\"));\nvar _util = require(\"util\");\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, \"default\": e }; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t3 in e) \"default\" !== _t3 && {}.hasOwnProperty.call(e, _t3) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t3)) && (i.get || i.set) ? o(f, _t3, i) : f[_t3] = e[_t3]); return f; })(e, t); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }\nfunction _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }\nfunction _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError(\"Cannot initialize the same private elements twice on an object\"); }\nfunction _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }\nfunction _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }\nfunction _assertClassBrand(e, t, n) { if (\"function\" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError(\"Private element is not present on this object\"); }\nfunction _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }\nfunction _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", { writable: !1 }), e; }\nfunction _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\"); }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(t, e) { if (e && (\"object\" == _typeof(e) || \"function\" == typeof e)) return e; if (void 0 !== e) throw new TypeError(\"Derived constructors may only return object or undefined\"); return _assertThisInitialized(t); }\nfunction _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); return e; }\nfunction _inherits(t, e) { if (\"function\" != typeof e && null !== e) throw new TypeError(\"Super expression must either be null or a function\"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, \"prototype\", { writable: !1 }), e && _setPrototypeOf(t, e); }\nfunction _wrapNativeSuper(t) { var r = \"function\" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if (\"function\" != typeof t) throw new TypeError(\"Super expression must either be null or a function\"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }\nfunction _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf(\"[native code]\"); } catch (n) { return \"function\" == typeof t; } }\nfunction _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }\nfunction _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = \"function\" == typeof Symbol ? Symbol : {}, n = r.iterator || \"@@iterator\", o = r.toStringTag || \"@@toStringTag\"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, \"_invoke\", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError(\"Generator is already running\"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = \"next\"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError(\"iterator result is not an object\"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i[\"return\"]) && t.call(i), c < 2 && (u = TypeError(\"The iterator does not provide a '\" + o + \"' method\"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, \"GeneratorFunction\")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, \"constructor\", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction), GeneratorFunction.displayName = \"GeneratorFunction\", _regeneratorDefine2(GeneratorFunctionPrototype, o, \"GeneratorFunction\"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, \"Generator\"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, \"toString\", function () { return \"[object Generator]\"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }\nfunction _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, \"\", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o(\"next\", 0), o(\"throw\", 1), o(\"return\", 2); } }, _regeneratorDefine2(e, r, n, t); }\nfunction asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }\nfunction _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n); } _next(void 0); }); }; } /**\n * Copyright 2018 Google LLC\n *\n * Distributed under MIT license.\n * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n */\nvar readFile = fs.readFile ? (0, _util.promisify)(fs.readFile) : /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {\n return _regenerator().w(function (_context) {\n while (1) switch (_context.n) {\n case 0:\n throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');\n case 1:\n return _context.a(2);\n }\n }, _callee);\n}));\nvar GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';\nvar GOOGLE_REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke?token=';\nvar ErrorWithCode = /*#__PURE__*/function (_Error) {\n function ErrorWithCode(message, code) {\n var _this;\n _classCallCheck(this, ErrorWithCode);\n _this = _callSuper(this, ErrorWithCode, [message]);\n _defineProperty(_this, \"code\", void 0);\n _this.code = code;\n return _this;\n }\n _inherits(ErrorWithCode, _Error);\n return _createClass(ErrorWithCode);\n}(/*#__PURE__*/_wrapNativeSuper(Error));\nvar _inFlightRequest = /*#__PURE__*/new WeakMap();\nvar _GoogleToken_brand = /*#__PURE__*/new WeakSet();\nvar GoogleToken = exports.GoogleToken = /*#__PURE__*/function () {\n /**\n * Create a GoogleToken.\n *\n * @param options Configuration object.\n */\n function GoogleToken(_options) {\n _classCallCheck(this, GoogleToken);\n _classPrivateMethodInitSpec(this, _GoogleToken_brand);\n _defineProperty(this, \"expiresAt\", void 0);\n _defineProperty(this, \"key\", void 0);\n _defineProperty(this, \"keyFile\", void 0);\n _defineProperty(this, \"iss\", void 0);\n _defineProperty(this, \"sub\", void 0);\n _defineProperty(this, \"scope\", void 0);\n _defineProperty(this, \"rawToken\", void 0);\n _defineProperty(this, \"tokenExpires\", void 0);\n _defineProperty(this, \"email\", void 0);\n _defineProperty(this, \"additionalClaims\", void 0);\n _defineProperty(this, \"eagerRefreshThresholdMillis\", void 0);\n _defineProperty(this, \"transporter\", {\n request: function request(opts) {\n return (0, _gaxios.request)(opts);\n }\n });\n _classPrivateFieldInitSpec(this, _inFlightRequest, void 0);\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, _options);\n }\n\n /**\n * Returns whether the token has expired.\n *\n * @return true if the token has expired, false otherwise.\n */\n return _createClass(GoogleToken, [{\n key: \"accessToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.access_token : undefined;\n }\n }, {\n key: \"idToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.id_token : undefined;\n }\n }, {\n key: \"tokenType\",\n get: function get() {\n return this.rawToken ? this.rawToken.token_type : undefined;\n }\n }, {\n key: \"refreshToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.refresh_token : undefined;\n }\n }, {\n key: \"hasExpired\",\n value: function hasExpired() {\n var now = new Date().getTime();\n if (this.rawToken && this.expiresAt) {\n return now >= this.expiresAt;\n } else {\n return true;\n }\n }\n\n /**\n * Returns whether the token will expire within eagerRefreshThresholdMillis\n *\n * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.\n */\n }, {\n key: \"isTokenExpiring\",\n value: function isTokenExpiring() {\n var _this$eagerRefreshThr;\n var now = new Date().getTime();\n var eagerRefreshThresholdMillis = (_this$eagerRefreshThr = this.eagerRefreshThresholdMillis) !== null && _this$eagerRefreshThr !== void 0 ? _this$eagerRefreshThr : 0;\n if (this.rawToken && this.expiresAt) {\n return this.expiresAt <= now + eagerRefreshThresholdMillis;\n } else {\n return true;\n }\n }\n\n /**\n * Returns a cached token or retrieves a new one from Google.\n *\n * @param callback The callback function.\n */\n }, {\n key: \"getToken\",\n value: function getToken(callback) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (_typeof(callback) === 'object') {\n opts = callback;\n callback = undefined;\n }\n opts = Object.assign({\n forceRefresh: false\n }, opts);\n if (callback) {\n var cb = callback;\n _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts).then(function (t) {\n return cb(null, t);\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts);\n }\n\n /**\n * Given a keyFile, extract the key and client email if available\n * @param keyFile Path to a json, pem, or p12 file that contains the key.\n * @returns an object with privateKey and clientEmail properties\n */\n }, {\n key: \"getCredentials\",\n value: (function () {\n var _getCredentials = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(keyFile) {\n var ext, key, body, privateKey, clientEmail, _privateKey, _t;\n return _regenerator().w(function (_context2) {\n while (1) switch (_context2.n) {\n case 0:\n ext = path.extname(keyFile);\n _t = ext;\n _context2.n = _t === '.json' ? 1 : _t === '.der' ? 4 : _t === '.crt' ? 4 : _t === '.pem' ? 4 : _t === '.p12' ? 6 : _t === '.pfx' ? 6 : 7;\n break;\n case 1:\n _context2.n = 2;\n return readFile(keyFile, 'utf8');\n case 2:\n key = _context2.v;\n body = JSON.parse(key);\n privateKey = body.private_key;\n clientEmail = body.client_email;\n if (!(!privateKey || !clientEmail)) {\n _context2.n = 3;\n break;\n }\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n case 3:\n return _context2.a(2, {\n privateKey: privateKey,\n clientEmail: clientEmail\n });\n case 4:\n _context2.n = 5;\n return readFile(keyFile, 'utf8');\n case 5:\n _privateKey = _context2.v;\n return _context2.a(2, {\n privateKey: _privateKey\n });\n case 6:\n throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 7:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 8:\n return _context2.a(2);\n }\n }, _callee2);\n }));\n function getCredentials(_x) {\n return _getCredentials.apply(this, arguments);\n }\n return getCredentials;\n }())\n }, {\n key: \"revokeToken\",\n value: function revokeToken(callback) {\n if (callback) {\n _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this).then(function () {\n return callback();\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this);\n }\n }]);\n}();\nfunction _getTokenAsync(_x2) {\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsync2() {\n _getTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(opts) {\n return _regenerator().w(function (_context3) {\n while (1) switch (_context3.n) {\n case 0:\n if (!(_classPrivateFieldGet(_inFlightRequest, this) && !opts.forceRefresh)) {\n _context3.n = 1;\n break;\n }\n return _context3.a(2, _classPrivateFieldGet(_inFlightRequest, this));\n case 1:\n _context3.p = 1;\n _context3.n = 2;\n return _classPrivateFieldSet(_inFlightRequest, this, _assertClassBrand(_GoogleToken_brand, this, _getTokenAsyncInner).call(this, opts));\n case 2:\n return _context3.a(2, _context3.v);\n case 3:\n _context3.p = 3;\n _classPrivateFieldSet(_inFlightRequest, this, undefined);\n return _context3.f(3);\n case 4:\n return _context3.a(2);\n }\n }, _callee3, this, [[1,, 3, 4]]);\n }));\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner(_x3) {\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner2() {\n _getTokenAsyncInner2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(opts) {\n var creds;\n return _regenerator().w(function (_context4) {\n while (1) switch (_context4.n) {\n case 0:\n if (!(this.isTokenExpiring() === false && opts.forceRefresh === false)) {\n _context4.n = 1;\n break;\n }\n return _context4.a(2, Promise.resolve(this.rawToken));\n case 1:\n if (!(!this.key && !this.keyFile)) {\n _context4.n = 2;\n break;\n }\n throw new Error('No key or keyFile set.');\n case 2:\n if (!(!this.key && this.keyFile)) {\n _context4.n = 4;\n break;\n }\n _context4.n = 3;\n return this.getCredentials(this.keyFile);\n case 3:\n creds = _context4.v;\n this.key = creds.privateKey;\n this.iss = creds.clientEmail || this.iss;\n if (!creds.clientEmail) {\n _assertClassBrand(_GoogleToken_brand, this, _ensureEmail).call(this);\n }\n case 4:\n return _context4.a(2, _assertClassBrand(_GoogleToken_brand, this, _requestToken).call(this));\n }\n }, _callee4, this);\n }));\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _ensureEmail() {\n if (!this.iss) {\n throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');\n }\n}\nfunction _revokeTokenAsync() {\n return _revokeTokenAsync2.apply(this, arguments);\n}\nfunction _revokeTokenAsync2() {\n _revokeTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {\n var url;\n return _regenerator().w(function (_context5) {\n while (1) switch (_context5.n) {\n case 0:\n if (this.accessToken) {\n _context5.n = 1;\n break;\n }\n throw new Error('No token to revoke.');\n case 1:\n url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;\n _context5.n = 2;\n return this.transporter.request({\n url: url,\n retry: true\n });\n case 2:\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, {\n email: this.iss,\n sub: this.sub,\n key: this.key,\n keyFile: this.keyFile,\n scope: this.scope,\n additionalClaims: this.additionalClaims\n });\n case 3:\n return _context5.a(2);\n }\n }, _callee5, this);\n }));\n return _revokeTokenAsync2.apply(this, arguments);\n}\n/**\n * Configure the GoogleToken for re-use.\n * @param {object} options Configuration object.\n */\nfunction _configure() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.rawToken = undefined;\n this.iss = options.email || options.iss;\n this.sub = options.sub;\n this.additionalClaims = options.additionalClaims;\n if (_typeof(options.scope) === 'object') {\n this.scope = options.scope.join(' ');\n } else {\n this.scope = options.scope;\n }\n this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;\n if (options.transporter) {\n this.transporter = options.transporter;\n }\n}\n/**\n * Request the token from Google.\n */\nfunction _requestToken() {\n return _requestToken2.apply(this, arguments);\n}\nfunction _requestToken2() {\n _requestToken2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {\n var iat, additionalClaims, payload, signedJWT, r, _response, _response2, body, desc, _t2;\n return _regenerator().w(function (_context6) {\n while (1) switch (_context6.n) {\n case 0:\n iat = Math.floor(new Date().getTime() / 1000);\n additionalClaims = this.additionalClaims || {};\n payload = Object.assign({\n iss: this.iss,\n scope: this.scope,\n aud: GOOGLE_TOKEN_URL,\n exp: iat + 3600,\n iat: iat,\n sub: this.sub\n }, additionalClaims);\n signedJWT = jws.sign({\n header: {\n alg: 'RS256'\n },\n payload: payload,\n secret: this.key\n });\n _context6.p = 1;\n _context6.n = 2;\n return this.transporter.request({\n method: 'POST',\n url: GOOGLE_TOKEN_URL,\n data: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: signedJWT\n }),\n responseType: 'json',\n retryConfig: {\n httpMethodsToRetry: ['POST']\n }\n });\n case 2:\n r = _context6.v;\n this.rawToken = r.data;\n this.expiresAt = r.data.expires_in === null || r.data.expires_in === undefined ? undefined : (iat + r.data.expires_in) * 1000;\n return _context6.a(2, this.rawToken);\n case 3:\n _context6.p = 3;\n _t2 = _context6.v;\n this.rawToken = undefined;\n this.tokenExpires = undefined;\n body = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};\n if (body.error) {\n desc = body.error_description ? \": \".concat(body.error_description) : '';\n _t2.message = \"\".concat(body.error).concat(desc);\n }\n throw _t2;\n case 4:\n return _context6.a(2);\n }\n }, _callee6, this, [[1, 3]]);\n }));\n return _requestToken2.apply(this, arguments);\n}", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWTAccess = void 0;\nconst jws = require(\"jws\");\nconst util_1 = require(\"../util\");\nconst DEFAULT_HEADER = {\n alg: 'RS256',\n typ: 'JWT',\n};\nclass JWTAccess {\n email;\n key;\n keyId;\n projectId;\n eagerRefreshThresholdMillis;\n cache = new util_1.LRUCache({\n capacity: 500,\n maxAge: 60 * 60 * 1000,\n });\n /**\n * JWTAccess service account credentials.\n *\n * Create a new access token by using the credential to create a new JWT token\n * that's recognized as the access token.\n *\n * @param email the service account email address.\n * @param key the private key that will be used to sign the token.\n * @param keyId the ID of the private key used to sign the token.\n */\n constructor(email, key, keyId, eagerRefreshThresholdMillis) {\n this.email = email;\n this.key = key;\n this.keyId = keyId;\n this.eagerRefreshThresholdMillis =\n eagerRefreshThresholdMillis ?? 5 * 60 * 1000;\n }\n /**\n * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url\n *\n * @param url The URI being authorized.\n * @param scopes The scope or scopes being authorized\n * @returns A string that returns the cached key.\n */\n getCachedKey(url, scopes) {\n let cacheKey = url;\n if (scopes && Array.isArray(scopes) && scopes.length) {\n cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;\n }\n else if (typeof scopes === 'string') {\n cacheKey = url ? `${url}_${scopes}` : scopes;\n }\n if (!cacheKey) {\n throw Error('Scopes or url must be provided');\n }\n return cacheKey;\n }\n /**\n * Get a non-expired access token, after refreshing if necessary.\n *\n * @param url The URI being authorized.\n * @param additionalClaims An object with a set of additional claims to\n * include in the payload.\n * @returns An object that includes the authorization header.\n */\n getRequestHeaders(url, additionalClaims, scopes) {\n // Return cached authorization headers, unless we are within\n // eagerRefreshThresholdMillis ms of them expiring:\n const key = this.getCachedKey(url, scopes);\n const cachedToken = this.cache.get(key);\n const now = Date.now();\n if (cachedToken &&\n cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {\n // Copying headers into a new `Headers` object to avoid potential leakage -\n // as this is a cache it is possible for multiple requests to reference this\n // same value.\n return new Headers(cachedToken.headers);\n }\n const iat = Math.floor(Date.now() / 1000);\n const exp = JWTAccess.getExpirationTime(iat);\n let defaultClaims;\n // Turn scopes into space-separated string\n if (Array.isArray(scopes)) {\n scopes = scopes.join(' ');\n }\n // If scopes are specified, sign with scopes\n if (scopes) {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n scope: scopes,\n exp,\n iat,\n };\n }\n else {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n aud: url,\n exp,\n iat,\n };\n }\n // if additionalClaims are provided, ensure they do not collide with\n // other required claims.\n if (additionalClaims) {\n for (const claim in defaultClaims) {\n if (additionalClaims[claim]) {\n throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);\n }\n }\n }\n const header = this.keyId\n ? { ...DEFAULT_HEADER, kid: this.keyId }\n : DEFAULT_HEADER;\n const payload = Object.assign(defaultClaims, additionalClaims);\n // Sign the jwt and add it to the cache\n const signedJWT = jws.sign({ header, payload, secret: this.key });\n const headers = new Headers({ authorization: `Bearer ${signedJWT}` });\n this.cache.set(key, {\n expiration: exp * 1000,\n headers,\n });\n return headers;\n }\n /**\n * Returns an expiration time for the JWT token.\n *\n * @param iat The issued at time for the JWT.\n * @returns An expiration time for the JWT.\n */\n static getExpirationTime(iat) {\n const exp = iat + 3600; // 3600 seconds = 1 hour\n return exp;\n }\n /**\n * Create a JWTAccess credentials instance using the given input options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n reject(new Error('Must pass in a stream containing the service account auth settings.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('data', chunk => (s += chunk))\n .on('error', reject)\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (err) {\n reject(err);\n }\n });\n });\n }\n}\nexports.JWTAccess = JWTAccess;\n//# sourceMappingURL=jwtaccess.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWT = void 0;\nconst gtoken_1 = require(\"gtoken\");\nconst jwtaccess_1 = require(\"./jwtaccess\");\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nclass JWT extends oauth2client_1.OAuth2Client {\n email;\n keyFile;\n key;\n keyId;\n defaultScopes;\n scopes;\n scope;\n subject;\n gtoken;\n additionalClaims;\n useJWTAccessWithScope;\n defaultServicePath;\n access;\n /**\n * JWT service account credentials.\n *\n * Retrieve access token using gtoken.\n *\n * @param options the\n */\n constructor(options = {}) {\n super(options);\n this.email = options.email;\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.keyId = options.keyId;\n this.scopes = options.scopes;\n this.subject = options.subject;\n this.additionalClaims = options.additionalClaims;\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };\n }\n /**\n * Creates a copy of the credential with the specified scopes.\n * @param scopes List of requested scopes or a single scope.\n * @return The cloned instance.\n */\n createScoped(scopes) {\n const jwt = new JWT(this);\n jwt.scopes = scopes;\n return jwt;\n }\n /**\n * Obtains the metadata to be sent with the request.\n *\n * @param url the URI being authorized.\n */\n async getRequestMetadataAsync(url) {\n url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;\n const useSelfSignedJWT = (!this.hasUserScopes() && url) ||\n (this.useJWTAccessWithScope && this.hasAnyScopes()) ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {\n throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);\n }\n if (!this.apiKey && useSelfSignedJWT) {\n if (this.additionalClaims &&\n this.additionalClaims.target_audience) {\n const { tokens } = await this.refreshToken();\n return {\n headers: this.addSharedMetadataHeaders(new Headers({\n authorization: `Bearer ${tokens.id_token}`,\n })),\n };\n }\n else {\n // no scopes have been set, but a uri has been provided. Use JWTAccess\n // credentials.\n if (!this.access) {\n this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);\n }\n let scopes;\n if (this.hasUserScopes()) {\n scopes = this.scopes;\n }\n else if (!url) {\n scopes = this.defaultScopes;\n }\n const useScopes = this.useJWTAccessWithScope ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, \n // Scopes take precedent over audience for signing,\n // so we only provide them if `useJWTAccessWithScope` is on or\n // if we are in a non-default universe\n useScopes ? scopes : undefined);\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n else if (this.hasAnyScopes() || this.apiKey) {\n return super.getRequestMetadataAsync(url);\n }\n else {\n // If no audience, apiKey, or scopes are provided, we should not attempt\n // to populate any headers:\n return { headers: new Headers() };\n }\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n // Create a new gToken for fetching an ID token\n const gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: { target_audience: targetAudience },\n transporter: this.transporter,\n });\n await gtoken.getToken({\n forceRefresh: true,\n });\n if (!gtoken.idToken) {\n throw new Error('Unknown error: Failed to fetch ID token');\n }\n return gtoken.idToken;\n }\n /**\n * Determine if there are currently scopes available.\n */\n hasUserScopes() {\n if (!this.scopes) {\n return false;\n }\n return this.scopes.length > 0;\n }\n /**\n * Are there any default or user scopes defined.\n */\n hasAnyScopes() {\n if (this.scopes && this.scopes.length > 0)\n return true;\n if (this.defaultScopes && this.defaultScopes.length > 0)\n return true;\n return false;\n }\n authorize(callback) {\n if (callback) {\n this.authorizeAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.authorizeAsync();\n }\n }\n async authorizeAsync() {\n const result = await this.refreshToken();\n if (!result) {\n throw new Error('No result returned');\n }\n this.credentials = result.tokens;\n this.credentials.refresh_token = 'jwt-placeholder';\n this.key = this.gtoken.key;\n this.email = this.gtoken.iss;\n return result.tokens;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken ignored\n * @private\n */\n async refreshTokenNoCache() {\n const gtoken = this.createGToken();\n const token = await gtoken.getToken({\n forceRefresh: this.isTokenExpiring(),\n });\n const tokens = {\n access_token: token.access_token,\n token_type: 'Bearer',\n expiry_date: gtoken.expiresAt,\n id_token: gtoken.idToken,\n };\n this.emit('tokens', tokens);\n return { res: null, tokens };\n }\n /**\n * Create a gToken if it doesn't already exist.\n */\n createGToken() {\n if (!this.gtoken) {\n this.gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: this.additionalClaims,\n transporter: this.transporter,\n });\n }\n return this.gtoken;\n }\n /**\n * Create a JWT credentials instance using the given input options.\n * @param json The input object.\n *\n * @remarks\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the service account auth settings.');\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n });\n }\n /**\n * Creates a JWT credentials instance using an API Key for authentication.\n * @param apiKey The API Key in string form.\n */\n fromAPIKey(apiKey) {\n if (typeof apiKey !== 'string') {\n throw new Error('Must provide an API Key string.');\n }\n this.apiKey = apiKey;\n }\n /**\n * Using the key or keyFile on the JWT client, obtain an object that contains\n * the key and the client email.\n */\n async getCredentials() {\n if (this.key) {\n return { private_key: this.key, client_email: this.email };\n }\n else if (this.keyFile) {\n const gtoken = this.createGToken();\n const creds = await gtoken.getCredentials(this.keyFile);\n return { private_key: creds.privateKey, client_email: creds.clientEmail };\n }\n throw new Error('A key or a keyFile must be provided to getCredentials.');\n }\n}\nexports.JWT = JWT;\n//# sourceMappingURL=jwtclient.js.map", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nexports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';\nclass UserRefreshClient extends oauth2client_1.OAuth2Client {\n // TODO: refactor tests to make this private\n // In a future gts release, the _propertyName rule will be lifted.\n // This is also a hard one because `this.refreshToken` is a function.\n _refreshToken;\n /**\n * The User Refresh Token client.\n *\n * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n */\n constructor(optionsOrClientId, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n refreshToken, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n eagerRefreshThresholdMillis, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n forceRefreshOnFailure) {\n const opts = optionsOrClientId && typeof optionsOrClientId === 'object'\n ? optionsOrClientId\n : {\n clientId: optionsOrClientId,\n clientSecret,\n refreshToken,\n eagerRefreshThresholdMillis,\n forceRefreshOnFailure,\n };\n super(opts);\n this._refreshToken = opts.refreshToken;\n this.credentials.refresh_token = opts.refreshToken;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken An ignored refreshToken..\n * @param callback Optional callback.\n */\n async refreshTokenNoCache() {\n return super.refreshTokenNoCache(this._refreshToken);\n }\n async fetchIdToken(targetAudience) {\n const opts = {\n ...UserRefreshClient.RETRY_CONFIG,\n url: this.endpoints.oauth2TokenUrl,\n method: 'POST',\n data: new URLSearchParams({\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n refresh_token: this._refreshToken,\n target_audience: targetAudience,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken');\n const res = await this.transporter.request(opts);\n return res.data.id_token;\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the user refresh token');\n }\n if (json.type !== 'authorized_user') {\n throw new Error('The incoming JSON object does not have the \"authorized_user\" type');\n }\n if (!json.client_id) {\n throw new Error('The incoming JSON object does not contain a client_id field');\n }\n if (!json.client_secret) {\n throw new Error('The incoming JSON object does not contain a client_secret field');\n }\n if (!json.refresh_token) {\n throw new Error('The incoming JSON object does not contain a refresh_token field');\n }\n this._clientId = json.client_id;\n this._clientSecret = json.client_secret;\n this._refreshToken = json.refresh_token;\n this.credentials.refresh_token = json.refresh_token;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n async fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n return reject(new Error('Must pass in a stream containing the user refresh token.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n return resolve();\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n static fromJSON(json) {\n const client = new UserRefreshClient();\n client.fromJSON(json);\n return client;\n }\n}\nexports.UserRefreshClient = UserRefreshClient;\n//# sourceMappingURL=refreshclient.js.map", "\"use strict\";\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nexports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';\nclass Impersonated extends oauth2client_1.OAuth2Client {\n sourceClient;\n targetPrincipal;\n targetScopes;\n delegates;\n lifetime;\n endpoint;\n /**\n * Impersonated service account credentials.\n *\n * Create a new access token by impersonating another service account.\n *\n * Impersonated Credentials allowing credentials issued to a user or\n * service account to impersonate another. The source project using\n * Impersonated Credentials must enable the \"IAMCredentials\" API.\n * Also, the target service account must grant the orginating principal\n * the \"Service Account Token Creator\" IAM role.\n *\n * @param {object} options - The configuration object.\n * @param {object} [options.sourceClient] the source credential used as to\n * acquire the impersonated credentials.\n * @param {string} [options.targetPrincipal] the service account to\n * impersonate.\n * @param {string[]} [options.delegates] the chained list of delegates\n * required to grant the final access_token. If set, the sequence of\n * identities must have \"Service Account Token Creator\" capability granted to\n * the preceding identity. For example, if set to [serviceAccountB,\n * serviceAccountC], the sourceCredential must have the Token Creator role on\n * serviceAccountB. serviceAccountB must have the Token Creator on\n * serviceAccountC. Finally, C must have Token Creator on target_principal.\n * If left unset, sourceCredential must have that role on targetPrincipal.\n * @param {string[]} [options.targetScopes] scopes to request during the\n * authorization grant.\n * @param {number} [options.lifetime] number of seconds the delegated\n * credential should be valid for up to 3600 seconds by default, or 43,200\n * seconds by extending the token's lifetime, see:\n * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth\n * @param {string} [options.endpoint] api endpoint override.\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = {\n expiry_date: 1,\n refresh_token: 'impersonated-placeholder',\n };\n this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client();\n this.targetPrincipal = options.targetPrincipal ?? '';\n this.delegates = options.delegates ?? [];\n this.targetScopes = options.targetScopes ?? [];\n this.lifetime = options.lifetime ?? 3600;\n const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (!usingExplicitUniverseDomain) {\n // override the default universe with the source's universe\n this.universeDomain = this.sourceClient.universeDomain;\n }\n else if (this.sourceClient.universeDomain !== this.universeDomain) {\n // non-default universe and is not matching the source - this could be a credential leak\n throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);\n }\n this.endpoint =\n options.endpoint ?? `https://iamcredentials.${this.universeDomain}`;\n }\n /**\n * Signs some bytes.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}\n * @param blobToSign String to sign.\n *\n * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string\n */\n async sign(blobToSign) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:signBlob`;\n const body = {\n delegates: this.delegates,\n payload: Buffer.from(blobToSign).toString('base64'),\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data;\n }\n /** The service account email to be impersonated. */\n getTargetPrincipal() {\n return this.targetPrincipal;\n }\n /**\n * Refreshes the access token.\n */\n async refreshToken() {\n try {\n await this.sourceClient.getAccessToken();\n const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;\n const u = `${this.endpoint}/v1/${name}:generateAccessToken`;\n const body = {\n delegates: this.delegates,\n scope: this.targetScopes,\n lifetime: this.lifetime + 's',\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n const tokenResponse = res.data;\n this.credentials.access_token = tokenResponse.accessToken;\n this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);\n return {\n tokens: this.credentials,\n res,\n };\n }\n catch (error) {\n if (!(error instanceof Error))\n throw error;\n let status = 0;\n let message = '';\n if (error instanceof gaxios_1.GaxiosError) {\n status = error?.response?.data?.error?.status;\n message = error?.response?.data?.error?.message;\n }\n if (status && message) {\n error.message = `${status}: unable to impersonate: ${message}`;\n throw error;\n }\n else {\n error.message = `unable to impersonate: ${error}`;\n throw error;\n }\n }\n }\n /**\n * Generates an OpenID Connect ID token for a service account.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}\n *\n * @param targetAudience the audience for the fetched ID token.\n * @param options the for the request\n * @return an OpenID Connect ID token\n */\n async fetchIdToken(targetAudience, options) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:generateIdToken`;\n const body = {\n delegates: this.delegates,\n audience: targetAudience,\n includeEmail: options?.includeEmail ?? true,\n useEmailAzp: options?.includeEmail ?? true,\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data.token;\n }\n}\nexports.Impersonated = Impersonated;\n//# sourceMappingURL=impersonated.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuthClientAuthHandler = void 0;\nexports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** List of HTTP methods that accept request bodies. */\nconst METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];\n/**\n * Abstract class for handling client authentication in OAuth-based\n * operations.\n * When request-body client authentication is used, only application/json and\n * application/x-www-form-urlencoded content types for HTTP methods that support\n * request bodies are supported.\n */\nclass OAuthClientAuthHandler {\n #crypto = (0, crypto_1.createCrypto)();\n #clientAuthentication;\n transporter;\n /**\n * Instantiates an OAuth client authentication handler.\n * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.\n */\n constructor(options) {\n if (options && 'clientId' in options) {\n this.#clientAuthentication = options;\n this.transporter = new gaxios_1.Gaxios();\n }\n else {\n this.#clientAuthentication = options?.clientAuthentication;\n this.transporter = options?.transporter || new gaxios_1.Gaxios();\n }\n }\n /**\n * Applies client authentication on the OAuth request's headers or POST\n * body but does not process the request.\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n applyClientAuthenticationOptions(opts, bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n // Inject authenticated header.\n this.injectAuthenticatedHeaders(opts, bearerToken);\n // Inject authenticated request body.\n if (!bearerToken) {\n this.injectAuthenticatedRequestBody(opts);\n }\n }\n /**\n * Applies client authentication on the request's header if either\n * basic authentication or bearer token authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n injectAuthenticatedHeaders(opts, bearerToken) {\n // Bearer token prioritized higher than basic Auth.\n if (bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Bearer ${bearerToken}`,\n });\n }\n else if (this.#clientAuthentication?.confidentialClientType === 'basic') {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n const clientId = this.#clientAuthentication.clientId;\n const clientSecret = this.#clientAuthentication.clientSecret || '';\n const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);\n gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Basic ${base64EncodedCreds}`,\n });\n }\n }\n /**\n * Applies client authentication on the request's body if request-body\n * client authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n */\n injectAuthenticatedRequestBody(opts) {\n if (this.#clientAuthentication?.confidentialClientType === 'request-body') {\n const method = (opts.method || 'GET').toUpperCase();\n if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {\n throw new Error(`${method} HTTP method does not support ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n // Get content-type\n const headers = new Headers(opts.headers);\n const contentType = headers.get('content-type');\n // Inject authenticated request body\n if (contentType?.startsWith('application/x-www-form-urlencoded') ||\n opts.data instanceof URLSearchParams) {\n const data = new URLSearchParams(opts.data ?? '');\n data.append('client_id', this.#clientAuthentication.clientId);\n data.append('client_secret', this.#clientAuthentication.clientSecret || '');\n opts.data = data;\n }\n else if (contentType?.startsWith('application/json')) {\n opts.data = opts.data || {};\n Object.assign(opts.data, {\n client_id: this.#clientAuthentication.clientId,\n client_secret: this.#clientAuthentication.clientSecret || '',\n });\n }\n else {\n throw new Error(`${contentType} content-types are not supported with ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.OAuthClientAuthHandler = OAuthClientAuthHandler;\n/**\n * Converts an OAuth error response to a native JavaScript Error.\n * @param resp The OAuth error response to convert to a native Error object.\n * @param err The optional original error. If provided, the error properties\n * will be copied to the new error.\n * @return The converted native Error object.\n */\nfunction getErrorFromOAuthErrorResponse(resp, err) {\n // Error response.\n const errorCode = resp.error;\n const errorDescription = resp.error_description;\n const errorUri = resp.error_uri;\n let message = `Error code ${errorCode}`;\n if (typeof errorDescription !== 'undefined') {\n message += `: ${errorDescription}`;\n }\n if (typeof errorUri !== 'undefined') {\n message += ` - ${errorUri}`;\n }\n const newError = new Error(message);\n // Copy properties from original error to newly generated error.\n if (err) {\n const keys = Object.keys(err);\n if (err.stack) {\n // Copy error.stack if available.\n keys.push('stack');\n }\n keys.forEach(key => {\n // Do not overwrite the message field.\n if (key !== 'message') {\n Object.defineProperty(newError, key, {\n value: err[key],\n writable: false,\n enumerable: true,\n });\n }\n });\n }\n return newError;\n}\n//# sourceMappingURL=oauth2common.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StsCredentials = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst util_1 = require(\"../util\");\n/**\n * Implements the OAuth 2.0 token exchange based on\n * https://tools.ietf.org/html/rfc8693\n */\nclass StsCredentials extends oauth2common_1.OAuthClientAuthHandler {\n #tokenExchangeEndpoint;\n /**\n * Initializes an STS credentials instance.\n *\n * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.\n * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.\n */\n constructor(options = {\n tokenExchangeEndpoint: '',\n }, \n /**\n * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead\n */\n clientAuthentication) {\n if (typeof options !== 'object' || options instanceof URL) {\n options = {\n tokenExchangeEndpoint: options,\n clientAuthentication,\n };\n }\n super(options);\n this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint;\n }\n /**\n * Exchanges the provided token for another type of token based on the\n * rfc8693 spec.\n * @param stsCredentialsOptions The token exchange options used to populate\n * the token exchange request.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @param options Optional additional GCP-specific non-spec defined options\n * to send with the request.\n * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`\n * @return A promise that resolves with the token exchange response containing\n * the requested token and its expiration time.\n */\n async exchangeToken(stsCredentialsOptions, headers, options) {\n const values = {\n grant_type: stsCredentialsOptions.grantType,\n resource: stsCredentialsOptions.resource,\n audience: stsCredentialsOptions.audience,\n scope: stsCredentialsOptions.scope?.join(' '),\n requested_token_type: stsCredentialsOptions.requestedTokenType,\n subject_token: stsCredentialsOptions.subjectToken,\n subject_token_type: stsCredentialsOptions.subjectTokenType,\n actor_token: stsCredentialsOptions.actingParty?.actorToken,\n actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,\n // Non-standard GCP-specific options.\n options: options && JSON.stringify(options),\n };\n const opts = {\n ...StsCredentials.RETRY_CONFIG,\n url: this.#tokenExchangeEndpoint.toString(),\n method: 'POST',\n headers,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'exchangeToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const stsSuccessfulResponse = response.data;\n stsSuccessfulResponse.res = response;\n return stsSuccessfulResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\nexports.StsCredentials = StsCredentials;\n//# sourceMappingURL=stscredentials.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\nconst util_1 = require(\"../util\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/** The default OAuth scope to request when none is provided. */\nconst DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';\n/** Default impersonated token lifespan in seconds.*/\nconst DEFAULT_TOKEN_LIFESPAN = 3600;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * The credentials JSON file type for external account clients.\n * There are 3 types of JSON configs:\n * 1. authorized_user => Google end user credential\n * 2. service_account => Google service account credential\n * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)\n */\nexports.EXTERNAL_ACCOUNT_TYPE = 'external_account';\n/**\n * Cloud resource manager URL used to retrieve project information.\n *\n * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead\n **/\nexports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';\n/** The workforce audience pattern. */\nconst WORKFORCE_AUDIENCE_PATTERN = '//iam\\\\.googleapis\\\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token';\n/**\n * Base external account client. This is used to instantiate AuthClients for\n * exchanging external account credentials for GCP access token and authorizing\n * requests to GCP APIs.\n * The base class implements common logic for exchanging various type of\n * external credentials for GCP access token. The logic of determining and\n * retrieving the external credential based on the environment and\n * credential_source will be left for the subclasses.\n */\nclass BaseExternalAccountClient extends authclient_1.AuthClient {\n /**\n * OAuth scopes for the GCP access token to use. When not provided,\n * the default https://www.googleapis.com/auth/cloud-platform is\n * used.\n */\n scopes;\n projectNumber;\n audience;\n subjectTokenType;\n stsCredential;\n clientAuth;\n credentialSourceType;\n cachedAccessToken;\n serviceAccountImpersonationUrl;\n serviceAccountImpersonationLifetime;\n workforcePoolUserProject;\n configLifetimeRequested;\n tokenUrl;\n /**\n * @example\n * ```ts\n * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');\n * ```\n */\n cloudResourceManagerURL;\n supplierContext;\n /**\n * A pending access token request. Used for concurrent calls.\n */\n #pendingAccessToken = null;\n /**\n * Instantiate a BaseExternalAccountClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const type = opts.get('type');\n if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) {\n throw new Error(`Expected \"${exports.EXTERNAL_ACCOUNT_TYPE}\" type but ` +\n `received \"${options.type}\"`);\n }\n const clientId = opts.get('client_id');\n const clientSecret = opts.get('client_secret');\n this.tokenUrl =\n opts.get('token_url') ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain);\n const subjectTokenType = opts.get('subject_token_type');\n const workforcePoolUserProject = opts.get('workforce_pool_user_project');\n const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url');\n const serviceAccountImpersonation = opts.get('service_account_impersonation');\n const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds');\n this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') ||\n `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);\n if (clientId) {\n this.clientAuth = {\n confidentialClientType: 'basic',\n clientId,\n clientSecret,\n };\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: this.tokenUrl,\n clientAuthentication: this.clientAuth,\n });\n this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE];\n this.cachedAccessToken = null;\n this.audience = opts.get('audience');\n this.subjectTokenType = subjectTokenType;\n this.workforcePoolUserProject = workforcePoolUserProject;\n const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);\n if (this.workforcePoolUserProject &&\n !this.audience.match(workforceAudiencePattern)) {\n throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +\n 'credentials.');\n }\n this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;\n this.serviceAccountImpersonationLifetime =\n serviceAccountImpersonationLifetime;\n if (this.serviceAccountImpersonationLifetime) {\n this.configLifetimeRequested = true;\n }\n else {\n this.configLifetimeRequested = false;\n this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;\n }\n this.projectNumber = this.getProjectNumber(this.audience);\n this.supplierContext = {\n audience: this.audience,\n subjectTokenType: this.subjectTokenType,\n transporter: this.transporter,\n };\n }\n /** The service account email to be impersonated, if available. */\n getServiceAccountEmail() {\n if (this.serviceAccountImpersonationUrl) {\n if (this.serviceAccountImpersonationUrl.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84}\n **/\n throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);\n }\n // Parse email from URL. The formal looks as follows:\n // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken\n const re = /serviceAccounts\\/(?[^:]+):generateAccessToken$/;\n const result = re.exec(this.serviceAccountImpersonationUrl);\n return result?.groups?.email || null;\n }\n return null;\n }\n /**\n * Provides a mechanism to inject GCP access tokens directly.\n * When the provided credential expires, a new credential, using the\n * external account options, is retrieved.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n super.setCredentials(credentials);\n this.cachedAccessToken = credentials;\n }\n /**\n * @return A promise that resolves with the current GCP access token\n * response. If the current credential is expired, a new one is retrieved.\n */\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * @return A promise that resolves with the project ID corresponding to the\n * current workload identity pool or current workforce pool if\n * determinable. For workforce pool credential, it returns the project ID\n * corresponding to the workforcePoolUserProject.\n * This is introduced to match the current pattern of using the Auth\n * library:\n * const projectId = await auth.getProjectId();\n * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;\n * const res = await client.request({ url });\n * The resource may not have permission\n * (resourcemanager.projects.get) to call this API or the required\n * scopes may not be selected:\n * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes\n */\n async getProjectId() {\n const projectNumber = this.projectNumber || this.workforcePoolUserProject;\n if (this.projectId) {\n // Return previously determined project ID.\n return this.projectId;\n }\n else if (projectNumber) {\n // Preferable not to use request() to avoid retrial policies.\n const headers = await this.getRequestHeaders();\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n headers,\n url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getProjectId');\n const response = await this.transporter.request(opts);\n this.projectId = response.data.projectId;\n return this.projectId;\n }\n return null;\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * External credentials are exchanged for GCP access tokens via the token\n * exchange endpoint and other settings provided in the client options\n * object.\n * If the service_account_impersonation_url is provided, an additional\n * step to exchange the external account GCP access token for a service\n * account impersonated token is performed.\n * @return A promise that resolves with the fresh GCP access tokens.\n */\n async refreshAccessTokenAsync() {\n // Use an existing access token request, or cache a new one\n this.#pendingAccessToken =\n this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();\n try {\n return await this.#pendingAccessToken;\n }\n finally {\n // clear pending access token for future requests\n this.#pendingAccessToken = null;\n }\n }\n async #internalRefreshAccessTokenAsync() {\n // Retrieve the external credential.\n const subjectToken = await this.retrieveSubjectToken();\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n audience: this.audience,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken,\n subjectTokenType: this.subjectTokenType,\n // generateAccessToken requires the provided access token to have\n // scopes:\n // https://www.googleapis.com/auth/iam or\n // https://www.googleapis.com/auth/cloud-platform\n // The new service account access token scopes will match the user\n // provided ones.\n scope: this.serviceAccountImpersonationUrl\n ? [DEFAULT_OAUTH_SCOPE]\n : this.getScopesArray(),\n };\n // Exchange the external credentials for a GCP access token.\n // Client auth is prioritized over passing the workforcePoolUserProject\n // parameter for STS token exchange.\n const additionalOptions = !this.clientAuth && this.workforcePoolUserProject\n ? { userProject: this.workforcePoolUserProject }\n : undefined;\n const additionalHeaders = new Headers({\n 'x-goog-api-client': this.getMetricsHeaderValue(),\n });\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);\n if (this.serviceAccountImpersonationUrl) {\n this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);\n }\n else if (stsResponse.expires_in) {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,\n res: stsResponse.res,\n };\n }\n else {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n res: stsResponse.res,\n };\n }\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedAccessToken.expiry_date,\n access_token: this.cachedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedAccessToken;\n }\n /**\n * Returns the workload identity pool project number if it is determinable\n * from the audience resource name.\n * @param audience The STS audience used to determine the project number.\n * @return The project number associated with the workload identity pool, if\n * this can be determined from the STS audience field. Otherwise, null is\n * returned.\n */\n getProjectNumber(audience) {\n // STS audience pattern:\n // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...\n const match = audience.match(/\\/projects\\/([^/]+)/);\n if (!match) {\n return null;\n }\n return match[1];\n }\n /**\n * Exchanges an external account GCP access token for a service\n * account impersonated access token using iamcredentials\n * GenerateAccessToken API.\n * @param token The access token to exchange for a service account access\n * token.\n * @return A promise that resolves with the service account impersonated\n * credentials response.\n */\n async getImpersonatedAccessToken(token) {\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n url: this.serviceAccountImpersonationUrl,\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${token}`,\n },\n data: {\n scope: this.getScopesArray(),\n lifetime: this.serviceAccountImpersonationLifetime + 's',\n },\n };\n authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken');\n const response = await this.transporter.request(opts);\n const successResponse = response.data;\n return {\n access_token: successResponse.accessToken,\n // Convert from ISO format to timestamp.\n expiry_date: new Date(successResponse.expireTime).getTime(),\n res: response,\n };\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param accessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(accessToken) {\n const now = new Date().getTime();\n return accessToken.expiry_date\n ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n /**\n * @return The list of scopes for the requested GCP access token.\n */\n getScopesArray() {\n // Since scopes can be provided as string or array, the type should\n // be normalized.\n if (typeof this.scopes === 'string') {\n return [this.scopes];\n }\n return this.scopes || [DEFAULT_OAUTH_SCOPE];\n }\n getMetricsHeaderValue() {\n const nodeVersion = process.version.replace(/^v/, '');\n const saImpersonation = this.serviceAccountImpersonationUrl !== undefined;\n const credentialSourceType = this.credentialSourceType\n ? this.credentialSourceType\n : 'unknown';\n return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;\n }\n getTokenUrl() {\n return this.tokenUrl;\n }\n}\nexports.BaseExternalAccountClient = BaseExternalAccountClient;\n//# sourceMappingURL=baseexternalclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileSubjectTokenSupplier = void 0;\nconst util_1 = require(\"util\");\nconst fs = require(\"fs\");\n// fs.readfile is undefined in browser karma tests causing\n// `npm run browser-test` to fail as test.oauth2.ts imports this file via\n// src/index.ts.\n// Fallback to void function to avoid promisify throwing a TypeError.\nconst readFile = (0, util_1.promisify)(fs.readFile ?? (() => { }));\nconst realpath = (0, util_1.promisify)(fs.realpath ?? (() => { }));\nconst lstat = (0, util_1.promisify)(fs.lstat ?? (() => { }));\n/**\n * Internal subject token supplier implementation used when a file location\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass FileSubjectTokenSupplier {\n filePath;\n formatType;\n subjectTokenFieldName;\n /**\n * Instantiates a new file based subject token supplier.\n * @param opts The file subject token supplier options to build the supplier\n * with.\n */\n constructor(opts) {\n this.filePath = opts.filePath;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n }\n /**\n * Returns the subject token stored at the file specified in the constructor.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken() {\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n let parsedFilePath = this.filePath;\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n parsedFilePath = await realpath(parsedFilePath);\n if (!(await lstat(parsedFilePath)).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n let subjectToken;\n const rawText = await readFile(parsedFilePath, { encoding: 'utf8' });\n if (this.formatType === 'text') {\n subjectToken = rawText;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const json = JSON.parse(rawText);\n subjectToken = json[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source file');\n }\n return subjectToken;\n }\n}\nexports.FileSubjectTokenSupplier = FileSubjectTokenSupplier;\n//# sourceMappingURL=filesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UrlSubjectTokenSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal subject token supplier implementation used when a URL\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass UrlSubjectTokenSupplier {\n url;\n headers;\n formatType;\n subjectTokenFieldName;\n additionalGaxiosOptions;\n /**\n * Instantiates a URL subject token supplier.\n * @param opts The URL subject token supplier options to build the supplier with.\n */\n constructor(opts) {\n this.url = opts.url;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n this.headers = opts.headers;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Sends a GET request to the URL provided in the constructor and resolves\n * with the returned external subject token.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken(context) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.url,\n method: 'GET',\n headers: this.headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken');\n let subjectToken;\n if (this.formatType === 'text') {\n const response = await context.transporter.request(opts);\n subjectToken = response.data;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const response = await context.transporter.request(opts);\n subjectToken = response.data[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source URL');\n }\n return subjectToken;\n }\n}\nexports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;\n//# sourceMappingURL=urlsubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;\nconst util_1 = require(\"../util\");\nconst fs = require(\"fs\");\nconst crypto_1 = require(\"crypto\");\nconst https = require(\"https\");\nexports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG';\n/**\n * Thrown when the certificate source cannot be located or accessed.\n */\nclass CertificateSourceUnavailableError extends Error {\n constructor(message) {\n super(message);\n this.name = 'CertificateSourceUnavailableError';\n }\n}\nexports.CertificateSourceUnavailableError = CertificateSourceUnavailableError;\n/**\n * Thrown for invalid configuration that is not related to file availability.\n */\nclass InvalidConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = 'InvalidConfigurationError';\n }\n}\nexports.InvalidConfigurationError = InvalidConfigurationError;\n/**\n * A subject token supplier that uses a client certificate for authentication.\n * It provides the certificate chain as the subject token for identity federation.\n */\nclass CertificateSubjectTokenSupplier {\n certificateConfigPath;\n trustChainPath;\n cert;\n key;\n /**\n * Initializes a new instance of the CertificateSubjectTokenSupplier.\n * @param opts The configuration options for the supplier.\n */\n constructor(opts) {\n if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.');\n }\n if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.');\n }\n this.trustChainPath = opts.trustChainPath;\n this.certificateConfigPath = opts.certificateConfigLocation ?? '';\n }\n /**\n * Creates an HTTPS agent configured with the client certificate and private key for mTLS.\n * @returns An mTLS-configured https.Agent.\n */\n async createMtlsHttpsAgent() {\n if (!this.key || !this.cert) {\n throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key');\n }\n return new https.Agent({ key: this.key, cert: this.cert });\n }\n /**\n * Constructs the subject token, which is the base64-encoded certificate chain.\n * @returns A promise that resolves with the subject token.\n */\n async getSubjectToken() {\n // The \"subject token\" in this context is the processed certificate chain.\n this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();\n const { certPath, keyPath } = await this.#getCertAndKeyPaths();\n ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));\n return await this.#processChainFromPaths(this.cert);\n }\n /**\n * Resolves the absolute path to the certificate configuration file\n * by checking the \"certificate_config_location\" provided in the ADC file,\n * or the \"GOOGLE_API_CERTIFICATE_CONFIG\" environment variable\n * or in the default gcloud path.\n * @param overridePath An optional path to check first.\n * @returns The resolved file path.\n */\n async #resolveCertificateConfigFilePath() {\n // 1. Check for the override path from constructor options.\n const overridePath = this.certificateConfigPath;\n if (overridePath) {\n if (await (0, util_1.isValidFile)(overridePath)) {\n return overridePath;\n }\n throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);\n }\n // 2. Check the standard environment variable.\n const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];\n if (envPath) {\n if (await (0, util_1.isValidFile)(envPath)) {\n return envPath;\n }\n throw new CertificateSourceUnavailableError(`Path from environment variable \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" is invalid: ${envPath}`);\n }\n // 3. Check the well-known gcloud config location.\n const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();\n if (await (0, util_1.isValidFile)(wellKnownPath)) {\n return wellKnownPath;\n }\n // 4. If none are found, throw an error.\n throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' +\n `the \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" env var, and the gcloud path (${wellKnownPath}).`);\n }\n /**\n * Reads and parses the certificate config JSON file to extract the certificate and key paths.\n * @returns An object containing the certificate and key paths.\n */\n async #getCertAndKeyPaths() {\n const configPath = this.certificateConfigPath;\n let fileContents;\n try {\n fileContents = await fs.promises.readFile(configPath, 'utf8');\n }\n catch (err) {\n throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);\n }\n try {\n const config = JSON.parse(fileContents);\n const certPath = config?.cert_configs?.workload?.cert_path;\n const keyPath = config?.cert_configs?.workload?.key_path;\n if (!certPath || !keyPath) {\n throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required \"cert_path\" or \"key_path\" in the workload config.`);\n }\n return { certPath, keyPath };\n }\n catch (e) {\n if (e instanceof InvalidConfigurationError)\n throw e;\n throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`);\n }\n }\n /**\n * Reads and parses the cert and key files get their content and check valid format.\n * @returns An object containing the cert content and key content in buffer format.\n */\n async #getKeyAndCert(certPath, keyPath) {\n let cert, key;\n try {\n cert = await fs.promises.readFile(certPath);\n new crypto_1.X509Certificate(cert);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);\n }\n try {\n key = await fs.promises.readFile(keyPath);\n (0, crypto_1.createPrivateKey)(key);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);\n }\n return { cert, key };\n }\n /**\n * Reads the leaf certificate and trust chain, combines them,\n * and returns a JSON array of base64-encoded certificates.\n * @returns A stringified JSON array of the certificate chain.\n */\n async #processChainFromPaths(leafCertBuffer) {\n const leafCert = new crypto_1.X509Certificate(leafCertBuffer);\n // If no trust chain is provided, just use the successfully parsed leaf certificate.\n if (!this.trustChainPath) {\n return JSON.stringify([leafCert.raw.toString('base64')]);\n }\n // Handle the trust chain logic.\n try {\n const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8');\n const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];\n const chainCerts = pemBlocks.map((pem, index) => {\n try {\n return new crypto_1.X509Certificate(pem);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Throw a more precise error if a single certificate in the chain is invalid.\n throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);\n }\n });\n const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw));\n let finalChain;\n if (leafIndex === -1) {\n // Leaf not found, so prepend it to the chain.\n finalChain = [leafCert, ...chainCerts];\n }\n else if (leafIndex === 0) {\n // Leaf is already the first element, so the chain is correctly ordered.\n finalChain = chainCerts;\n }\n else {\n // Leaf is in the chain but not at the top, which is invalid.\n throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);\n }\n return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64')));\n }\n catch (err) {\n // Re-throw our specific configuration errors.\n if (err instanceof InvalidConfigurationError)\n throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);\n }\n }\n}\nexports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;\n//# sourceMappingURL=certificatesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdentityPoolClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst util_1 = require(\"../util\");\nconst filesubjecttokensupplier_1 = require(\"./filesubjecttokensupplier\");\nconst urlsubjecttokensupplier_1 = require(\"./urlsubjecttokensupplier\");\nconst certificatesubjecttokensupplier_1 = require(\"./certificatesubjecttokensupplier\");\nconst stscredentials_1 = require(\"./stscredentials\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * Defines the Url-sourced and file-sourced external account clients mainly\n * used for K8s and Azure workloads.\n */\nclass IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {\n subjectTokenSupplier;\n /**\n * Instantiate an IdentityPoolClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid file-sourced or\n * url-sourced credential or a workforce pool user project is provided\n * with a non workforce audience.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const subjectTokenSupplier = opts.get('subject_token_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !subjectTokenSupplier) {\n throw new Error('A credential source or subject token supplier must be specified.');\n }\n if (credentialSource && subjectTokenSupplier) {\n throw new Error('Only one of credential source or subject token supplier can be specified.');\n }\n if (subjectTokenSupplier) {\n this.subjectTokenSupplier = subjectTokenSupplier;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format'));\n // Text is the default format type.\n const formatType = formatOpts.get('type') || 'text';\n const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name');\n if (formatType !== 'json' && formatType !== 'text') {\n throw new Error(`Invalid credential_source format \"${formatType}\"`);\n }\n if (formatType === 'json' && !formatSubjectTokenFieldName) {\n throw new Error('Missing subject_token_field_name for JSON credential_source format');\n }\n const file = credentialSourceOpts.get('file');\n const url = credentialSourceOpts.get('url');\n const certificate = credentialSourceOpts.get('certificate');\n const headers = credentialSourceOpts.get('headers');\n if ((file && url) || (url && certificate) || (file && certificate)) {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n else if (file) {\n this.credentialSourceType = 'file';\n this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({\n filePath: file,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n });\n }\n else if (url) {\n this.credentialSourceType = 'url';\n this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({\n url: url,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n headers: headers,\n additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG,\n });\n }\n else if (certificate) {\n this.credentialSourceType = 'certificate';\n const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({\n useDefaultCertificateConfig: certificate.use_default_certificate_config,\n certificateConfigLocation: certificate.certificate_config_location,\n trustChainPath: certificate.trust_chain_path,\n });\n this.subjectTokenSupplier = certificateSubjecttokensupplier;\n }\n else {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n }\n }\n /**\n * Triggered when a external subject token is needed to be exchanged for a GCP\n * access token via GCP STS endpoint. Gets a subject token by calling\n * the configured {@link SubjectTokenSupplier}\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);\n if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {\n const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();\n this.stsCredential = new stscredentials_1.StsCredentials({\n tokenExchangeEndpoint: this.getTokenUrl(),\n clientAuthentication: this.clientAuth,\n transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }),\n });\n this.transporter = new gaxios_1.Gaxios({\n ...(this.transporter.defaults || {}),\n agent: mtlsAgent,\n });\n }\n return subjectToken;\n }\n}\nexports.IdentityPoolClient = IdentityPoolClient;\n//# sourceMappingURL=identitypoolclient.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsRequestSigner = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** AWS Signature Version 4 signing algorithm identifier. */\nconst AWS_ALGORITHM = 'AWS4-HMAC-SHA256';\n/**\n * The termination string for the AWS credential scope value as defined in\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n */\nconst AWS_REQUEST_TYPE = 'aws4_request';\n/**\n * Implements an AWS API request signer based on the AWS Signature Version 4\n * signing process.\n * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html\n */\nclass AwsRequestSigner {\n getCredentials;\n region;\n crypto;\n /**\n * Instantiates an AWS API request signer used to send authenticated signed\n * requests to AWS APIs based on the AWS Signature Version 4 signing process.\n * This also provides a mechanism to generate the signed request without\n * sending it.\n * @param getCredentials A mechanism to retrieve AWS security credentials\n * when needed.\n * @param region The AWS region to use.\n */\n constructor(getCredentials, region) {\n this.getCredentials = getCredentials;\n this.region = region;\n this.crypto = (0, crypto_1.createCrypto)();\n }\n /**\n * Generates the signed request for the provided HTTP request for calling\n * an AWS API. This follows the steps described at:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n * @param amzOptions The AWS request options that need to be signed.\n * @return A promise that resolves with the GaxiosOptions containing the\n * signed HTTP request parameters.\n */\n async getRequestOptions(amzOptions) {\n if (!amzOptions.url) {\n throw new RangeError('\"url\" is required in \"amzOptions\"');\n }\n // Stringify JSON requests. This will be set in the request body of the\n // generated signed request.\n const requestPayloadData = typeof amzOptions.data === 'object'\n ? JSON.stringify(amzOptions.data)\n : amzOptions.data;\n const url = amzOptions.url;\n const method = amzOptions.method || 'GET';\n const requestPayload = amzOptions.body || requestPayloadData;\n const additionalAmzHeaders = amzOptions.headers;\n const awsSecurityCredentials = await this.getCredentials();\n const uri = new URL(url);\n if (typeof requestPayload !== 'string' && requestPayload !== undefined) {\n throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);\n }\n const headerMap = await generateAuthenticationHeaderMap({\n crypto: this.crypto,\n host: uri.host,\n canonicalUri: uri.pathname,\n canonicalQuerystring: uri.search.slice(1),\n method,\n region: this.region,\n securityCredentials: awsSecurityCredentials,\n requestPayload,\n additionalAmzHeaders,\n });\n // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.\n const headers = gaxios_1.Gaxios.mergeHeaders(\n // Add x-amz-date if available.\n headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {\n authorization: headerMap.authorizationHeader,\n host: uri.host,\n }, additionalAmzHeaders || {});\n if (awsSecurityCredentials.token) {\n gaxios_1.Gaxios.mergeHeaders(headers, {\n 'x-amz-security-token': awsSecurityCredentials.token,\n });\n }\n const awsSignedReq = {\n url,\n method: method,\n headers,\n };\n if (requestPayload !== undefined) {\n awsSignedReq.body = requestPayload;\n }\n return awsSignedReq;\n }\n}\nexports.AwsRequestSigner = AwsRequestSigner;\n/**\n * Creates the HMAC-SHA256 hash of the provided message using the\n * provided key.\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The HMAC-SHA256 key to use.\n * @param msg The message to hash.\n * @return The computed hash bytes.\n */\nasync function sign(crypto, key, msg) {\n return await crypto.signWithHmacSha256(key, msg);\n}\n/**\n * Calculates the signing key used to calculate the signature for\n * AWS Signature Version 4 based on:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The AWS secret access key.\n * @param dateStamp The '%Y%m%d' date format.\n * @param region The AWS region.\n * @param serviceName The AWS service name, eg. sts.\n * @return The signing key bytes.\n */\nasync function getSigningKey(crypto, key, dateStamp, region, serviceName) {\n const kDate = await sign(crypto, `AWS4${key}`, dateStamp);\n const kRegion = await sign(crypto, kDate, region);\n const kService = await sign(crypto, kRegion, serviceName);\n const kSigning = await sign(crypto, kService, 'aws4_request');\n return kSigning;\n}\n/**\n * Generates the authentication header map needed for generating the AWS\n * Signature Version 4 signed request.\n *\n * @param option The options needed to compute the authentication header map.\n * @return The AWS authentication header map which constitutes of the following\n * components: amz-date, authorization header and canonical query string.\n */\nasync function generateAuthenticationHeaderMap(options) {\n const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders);\n const requestPayload = options.requestPayload || '';\n // iam.amazonaws.com host => iam service.\n // sts.us-east-2.amazonaws.com => sts service.\n const serviceName = options.host.split('.')[0];\n const now = new Date();\n // Format: '%Y%m%dT%H%M%SZ'.\n const amzDate = now\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.[0-9]+/, '');\n // Format: '%Y%m%d'.\n const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');\n // Add AWS token if available.\n if (options.securityCredentials.token) {\n additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token);\n }\n // Header keys need to be sorted alphabetically.\n const amzHeaders = gaxios_1.Gaxios.mergeHeaders({\n host: options.host,\n }, \n // Previously the date was not fixed with x-amz- and could be provided manually.\n // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req\n additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders);\n let canonicalHeaders = '';\n // TypeScript is missing `Headers#keys` at the time of writing\n const signedHeadersList = [\n ...amzHeaders.keys(),\n ].sort();\n signedHeadersList.forEach(key => {\n canonicalHeaders += `${key}:${amzHeaders.get(key)}\\n`;\n });\n const signedHeaders = signedHeadersList.join(';');\n const payloadHash = await options.crypto.sha256DigestHex(requestPayload);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n const canonicalRequest = `${options.method.toUpperCase()}\\n` +\n `${options.canonicalUri}\\n` +\n `${options.canonicalQuerystring}\\n` +\n `${canonicalHeaders}\\n` +\n `${signedHeaders}\\n` +\n `${payloadHash}`;\n const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n const stringToSign = `${AWS_ALGORITHM}\\n` +\n `${amzDate}\\n` +\n `${credentialScope}\\n` +\n (await options.crypto.sha256DigestHex(canonicalRequest));\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);\n const signature = await sign(options.crypto, signingKey, stringToSign);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html\n const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +\n `${credentialScope}, SignedHeaders=${signedHeaders}, ` +\n `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;\n return {\n // Do not return x-amz-date if date is available.\n amzDate: additionalAmzHeaders.has('date') ? undefined : amzDate,\n authorizationHeader,\n canonicalQuerystring: options.canonicalQuerystring,\n };\n}\n//# sourceMappingURL=awsrequestsigner.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefaultAwsSecurityCredentialsSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal AWS security credentials supplier implementation used by {@link AwsClient}\n * when a credential source is provided instead of a user defined supplier.\n * The logic is summarized as:\n * 1. If imdsv2_session_token_url is provided in the credential source, then\n * fetch the aws session token and include it in the headers of the\n * metadata requests. This is a requirement for IDMSv2 but optional\n * for IDMSv1.\n * 2. Retrieve AWS region from availability-zone.\n * 3a. Check AWS credentials in environment variables. If not found, get\n * from security-credentials endpoint.\n * 3b. Get AWS credentials from security-credentials endpoint. In order\n * to retrieve this, the AWS role needs to be determined by calling\n * security-credentials endpoint without any argument. Then the\n * credentials can be retrieved via: security-credentials/role_name\n * 4. Generate the signed request to AWS STS GetCallerIdentity action.\n * 5. Inject x-goog-cloud-target-resource into header and serialize the\n * signed request. This will be the subject-token to pass to GCP STS.\n */\nclass DefaultAwsSecurityCredentialsSupplier {\n regionUrl;\n securityCredentialsUrl;\n imdsV2SessionTokenUrl;\n additionalGaxiosOptions;\n /**\n * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information\n * from the credential_source stored in the ADC file.\n * @param opts The default aws security credentials supplier options object to\n * build the supplier with.\n */\n constructor(opts) {\n this.regionUrl = opts.regionUrl;\n this.securityCredentialsUrl = opts.securityCredentialsUrl;\n this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Returns the active AWS region. This first checks to see if the region\n * is available as an environment variable. If it is not, then the supplier\n * will call the region URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS region string.\n */\n async getAwsRegion(context) {\n // Priority order for region determination:\n // AWS_REGION > AWS_DEFAULT_REGION > metadata server.\n if (this.#regionFromEnv) {\n return this.#regionFromEnv;\n }\n const metadataHeaders = new Headers();\n if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n if (!this.regionUrl) {\n throw new RangeError('Unable to determine AWS region due to missing ' +\n '\"options.credential_source.region_url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.regionUrl,\n method: 'GET',\n headers: metadataHeaders,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion');\n const response = await context.transporter.request(opts);\n // Remove last character. For example, if us-east-2b is returned,\n // the region would be us-east-2.\n return response.data.substr(0, response.data.length - 1);\n }\n /**\n * Returns AWS security credentials. This first checks to see if the credentials\n * is available as environment variables. If it is not, then the supplier\n * will call the security credentials URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS security credentials.\n */\n async getAwsSecurityCredentials(context) {\n // Check environment variables for permanent credentials first.\n // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html\n if (this.#securityCredentialsFromEnv) {\n return this.#securityCredentialsFromEnv;\n }\n const metadataHeaders = new Headers();\n if (this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n // Since the role on a VM can change, we don't need to cache it.\n const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter);\n // Temporary credentials typically last for several hours.\n // Expiration is returned in response.\n // Consider future optimization of this logic to cache AWS tokens\n // until their natural expiration.\n const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter);\n return {\n accessKeyId: awsCreds.AccessKeyId,\n secretAccessKey: awsCreds.SecretAccessKey,\n token: awsCreds.Token,\n };\n }\n /**\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the IMDSv2 Session Token.\n */\n async #getImdsV2SessionToken(transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.imdsV2SessionTokenUrl,\n method: 'PUT',\n headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },\n };\n authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the assigned role to the current\n * AWS VM. This is needed for calling the security-credentials endpoint.\n */\n async #getAwsRoleName(headers, transporter) {\n if (!this.securityCredentialsUrl) {\n throw new Error('Unable to determine AWS role name due to missing ' +\n '\"options.credential_source.url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.securityCredentialsUrl,\n method: 'GET',\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * Retrieves the temporary AWS credentials by calling the security-credentials\n * endpoint as specified in the `credential_source` object.\n * @param roleName The role attached to the current VM.\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the temporary AWS credentials\n * needed for creating the GetCallerIdentity signed request.\n */\n async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: `${this.securityCredentialsUrl}/${roleName}`,\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials');\n const response = await transporter.request(opts);\n return response.data;\n }\n get #regionFromEnv() {\n // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION.\n // Only one is required.\n return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null);\n }\n get #securityCredentialsFromEnv() {\n // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required.\n if (process.env['AWS_ACCESS_KEY_ID'] &&\n process.env['AWS_SECRET_ACCESS_KEY']) {\n return {\n accessKeyId: process.env['AWS_ACCESS_KEY_ID'],\n secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],\n token: process.env['AWS_SESSION_TOKEN'],\n };\n }\n return null;\n }\n}\nexports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;\n//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsClient = void 0;\nconst awsrequestsigner_1 = require(\"./awsrequestsigner\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst defaultawssecuritycredentialssupplier_1 = require(\"./defaultawssecuritycredentialssupplier\");\nconst util_1 = require(\"../util\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * AWS external account client. This is used for AWS workloads, where\n * AWS STS GetCallerIdentity serialized signed requests are exchanged for\n * GCP access token.\n */\nclass AwsClient extends baseexternalclient_1.BaseExternalAccountClient {\n environmentId;\n awsSecurityCredentialsSupplier;\n regionalCredVerificationUrl;\n awsRequestSigner;\n region;\n static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254';\n /**\n * Instantiates an AwsClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid AWS credential.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !awsSecurityCredentialsSupplier) {\n throw new Error('A credential source or AWS security credentials supplier must be specified.');\n }\n if (credentialSource && awsSecurityCredentialsSupplier) {\n throw new Error('Only one of credential source or AWS security credentials supplier can be specified.');\n }\n if (awsSecurityCredentialsSupplier) {\n this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;\n this.regionalCredVerificationUrl =\n AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n this.environmentId = credentialSourceOpts.get('environment_id');\n // This is only required if the AWS region is not available in the\n // AWS_REGION or AWS_DEFAULT_REGION environment variables.\n const regionUrl = credentialSourceOpts.get('region_url');\n // This is only required if AWS security credentials are not available in\n // environment variables.\n const securityCredentialsUrl = credentialSourceOpts.get('url');\n const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url');\n this.awsSecurityCredentialsSupplier =\n new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({\n regionUrl: regionUrl,\n securityCredentialsUrl: securityCredentialsUrl,\n imdsV2SessionTokenUrl: imdsV2SessionTokenUrl,\n });\n this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url');\n this.credentialSourceType = 'aws';\n // Data validators.\n this.validateEnvironmentId();\n }\n this.awsRequestSigner = null;\n this.region = '';\n }\n validateEnvironmentId() {\n const match = this.environmentId?.match(/^(aws)(\\d+)$/);\n if (!match || !this.regionalCredVerificationUrl) {\n throw new Error('No valid AWS \"credential_source\" provided');\n }\n else if (parseInt(match[2], 10) !== 1) {\n throw new Error(`aws version \"${match[2]}\" is not supported in the current build.`);\n }\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint. This will call the\n * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS\n * Security Credentials, then use them to create a signed AWS STS request that\n * can be exchanged for a GCP access token.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Initialize AWS request signer if not already initialized.\n if (!this.awsRequestSigner) {\n this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);\n this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {\n return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);\n }, this.region);\n }\n // Generate signed request to AWS STS GetCallerIdentity API.\n // Use the required regional endpoint. Otherwise, the request will fail.\n const options = await this.awsRequestSigner.getRequestOptions({\n ...AwsClient.RETRY_CONFIG,\n url: this.regionalCredVerificationUrl.replace('{region}', this.region),\n method: 'POST',\n });\n // The GCP STS endpoint expects the headers to be formatted as:\n // [\n // {key: 'x-amz-date', value: '...'},\n // {key: 'authorization', value: '...'},\n // ...\n // ]\n // And then serialized as:\n // encodeURIComponent(JSON.stringify({\n // url: '...',\n // method: 'POST',\n // headers: [{key: 'x-amz-date', value: '...'}, ...]\n // }))\n const reformattedHeader = [];\n const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({\n // The full, canonical resource name of the workload identity pool\n // provider, with or without the HTTPS prefix.\n // Including this header as part of the signature is recommended to\n // ensure data integrity.\n 'x-goog-cloud-target-resource': this.audience,\n }, options.headers);\n // Reformat header to GCP STS expected format.\n extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));\n // Serialize the reformatted signed request.\n return encodeURIComponent(JSON.stringify({\n url: options.url,\n method: options.method,\n headers: reformattedHeader,\n }));\n }\n}\nexports.AwsClient = AwsClient;\n//# sourceMappingURL=awsclient.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;\nconst SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';\nconst OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';\nconst OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';\n/**\n * Defines the response of a 3rd party executable run by the pluggable auth client.\n */\nclass ExecutableResponse {\n /**\n * The version of the Executable response. Only version 1 is currently supported.\n */\n version;\n /**\n * Whether the executable ran successfully.\n */\n success;\n /**\n * The epoch time for expiration of the token in seconds.\n */\n expirationTime;\n /**\n * The type of subject token in the response, currently supported values are:\n * urn:ietf:params:oauth:token-type:saml2\n * urn:ietf:params:oauth:token-type:id_token\n * urn:ietf:params:oauth:token-type:jwt\n */\n tokenType;\n /**\n * The error code from the executable.\n */\n errorCode;\n /**\n * The error message from the executable.\n */\n errorMessage;\n /**\n * The subject token from the executable, format depends on tokenType.\n */\n subjectToken;\n /**\n * Instantiates an ExecutableResponse instance using the provided JSON object\n * from the output of the executable.\n * @param responseJson Response from a 3rd party executable, loaded from a\n * run of the executable or a cached output file.\n */\n constructor(responseJson) {\n // Check that the required fields exist in the json response.\n if (!responseJson.version) {\n throw new InvalidVersionFieldError(\"Executable response must contain a 'version' field.\");\n }\n if (responseJson.success === undefined) {\n throw new InvalidSuccessFieldError(\"Executable response must contain a 'success' field.\");\n }\n this.version = responseJson.version;\n this.success = responseJson.success;\n // Validate required fields for a successful response.\n if (this.success) {\n this.expirationTime = responseJson.expiration_time;\n this.tokenType = responseJson.token_type;\n // Validate token type field.\n if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {\n throw new InvalidTokenTypeFieldError(\"Executable response must contain a 'token_type' field when successful \" +\n `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n // Validate subject token.\n if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {\n if (!responseJson.saml_response) {\n throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n this.subjectToken = responseJson.saml_response;\n }\n else {\n if (!responseJson.id_token) {\n throw new InvalidSubjectTokenError(\"Executable response must contain a 'id_token' field when \" +\n `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);\n }\n this.subjectToken = responseJson.id_token;\n }\n }\n else {\n // Both code and message must be provided for unsuccessful responses.\n if (!responseJson.code) {\n throw new InvalidCodeFieldError(\"Executable response must contain a 'code' field when unsuccessful.\");\n }\n if (!responseJson.message) {\n throw new InvalidMessageFieldError(\"Executable response must contain a 'message' field when unsuccessful.\");\n }\n this.errorCode = responseJson.code;\n this.errorMessage = responseJson.message;\n }\n }\n /**\n * @return A boolean representing if the response has a valid token. Returns\n * true when the response was successful and the token is not expired.\n */\n isValid() {\n return !this.isExpired() && this.success;\n }\n /**\n * @return A boolean representing if the response is expired. Returns true if the\n * provided timeout has passed.\n */\n isExpired() {\n return (this.expirationTime !== undefined &&\n this.expirationTime < Math.round(Date.now() / 1000));\n }\n}\nexports.ExecutableResponse = ExecutableResponse;\n/**\n * An error thrown by the ExecutableResponse class.\n */\nclass ExecutableResponseError extends Error {\n constructor(message) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableResponseError = ExecutableResponseError;\n/**\n * An error thrown when the 'version' field in an executable response is missing or invalid.\n */\nclass InvalidVersionFieldError extends ExecutableResponseError {\n}\nexports.InvalidVersionFieldError = InvalidVersionFieldError;\n/**\n * An error thrown when the 'success' field in an executable response is missing or invalid.\n */\nclass InvalidSuccessFieldError extends ExecutableResponseError {\n}\nexports.InvalidSuccessFieldError = InvalidSuccessFieldError;\n/**\n * An error thrown when the 'expiration_time' field in an executable response is missing or invalid.\n */\nclass InvalidExpirationTimeFieldError extends ExecutableResponseError {\n}\nexports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;\n/**\n * An error thrown when the 'token_type' field in an executable response is missing or invalid.\n */\nclass InvalidTokenTypeFieldError extends ExecutableResponseError {\n}\nexports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;\n/**\n * An error thrown when the 'code' field in an executable response is missing or invalid.\n */\nclass InvalidCodeFieldError extends ExecutableResponseError {\n}\nexports.InvalidCodeFieldError = InvalidCodeFieldError;\n/**\n * An error thrown when the 'message' field in an executable response is missing or invalid.\n */\nclass InvalidMessageFieldError extends ExecutableResponseError {\n}\nexports.InvalidMessageFieldError = InvalidMessageFieldError;\n/**\n * An error thrown when the subject token in an executable response is missing or invalid.\n */\nclass InvalidSubjectTokenError extends ExecutableResponseError {\n}\nexports.InvalidSubjectTokenError = InvalidSubjectTokenError;\n//# sourceMappingURL=executable-response.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthHandler = exports.ExecutableError = void 0;\nconst executable_response_1 = require(\"./executable-response\");\nconst childProcess = require(\"child_process\");\nconst fs = require(\"fs\");\n/**\n * Error thrown from the executable run by PluggableAuthClient.\n */\nclass ExecutableError extends Error {\n /**\n * The exit code returned by the executable.\n */\n code;\n constructor(message, code) {\n super(`The executable failed with exit code: ${code} and error message: ${message}.`);\n this.code = code;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableError = ExecutableError;\n/**\n * A handler used to retrieve 3rd party token responses from user defined\n * executables and cached file output for the PluggableAuthClient class.\n */\nclass PluggableAuthHandler {\n commandComponents;\n timeoutMillis;\n outputFile;\n /**\n * Instantiates a PluggableAuthHandler instance using the provided\n * PluggableAuthHandlerOptions object.\n */\n constructor(options) {\n if (!options.command) {\n throw new Error('No command provided.');\n }\n this.commandComponents = PluggableAuthHandler.parseCommand(options.command);\n this.timeoutMillis = options.timeoutMillis;\n if (!this.timeoutMillis) {\n throw new Error('No timeoutMillis provided.');\n }\n this.outputFile = options.outputFile;\n }\n /**\n * Calls user provided executable to get a 3rd party subject token and\n * returns the response.\n * @param envMap a Map of additional Environment Variables required for\n * the executable.\n * @return A promise that resolves with the executable response.\n */\n retrieveResponseFromExecutable(envMap) {\n return new Promise((resolve, reject) => {\n // Spawn process to run executable using added environment variables.\n const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {\n env: { ...process.env, ...Object.fromEntries(envMap) },\n });\n let output = '';\n // Append stdout to output as executable runs.\n child.stdout.on('data', (data) => {\n output += data;\n });\n // Append stderr as executable runs.\n child.stderr.on('data', (err) => {\n output += err;\n });\n // Set up a timeout to end the child process and throw an error.\n const timeout = setTimeout(() => {\n // Kill child process and remove listeners so 'close' event doesn't get\n // read after child process is killed.\n child.removeAllListeners();\n child.kill();\n return reject(new Error('The executable failed to finish within the timeout specified.'));\n }, this.timeoutMillis);\n child.on('close', (code) => {\n // Cancel timeout if executable closes before timeout is reached.\n clearTimeout(timeout);\n if (code === 0) {\n // If the executable completed successfully, try to return the parsed response.\n try {\n const responseJson = JSON.parse(output);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n return resolve(response);\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n return reject(error);\n }\n return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));\n }\n }\n else {\n return reject(new ExecutableError(output, code.toString()));\n }\n });\n });\n }\n /**\n * Checks user provided output file for response from previous run of\n * executable and return the response if it exists, is formatted correctly, and is not expired.\n */\n async retrieveCachedResponse() {\n if (!this.outputFile || this.outputFile.length === 0) {\n return undefined;\n }\n let filePath;\n try {\n filePath = await fs.promises.realpath(this.outputFile);\n }\n catch {\n // If file path cannot be resolved, return undefined.\n return undefined;\n }\n if (!(await fs.promises.lstat(filePath)).isFile()) {\n // If path does not lead to file, return undefined.\n return undefined;\n }\n const responseString = await fs.promises.readFile(filePath, {\n encoding: 'utf8',\n });\n if (responseString === '') {\n return undefined;\n }\n try {\n const responseJson = JSON.parse(responseString);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n // Check if response is successful and unexpired.\n if (response.isValid()) {\n return new executable_response_1.ExecutableResponse(responseJson);\n }\n return undefined;\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n throw error;\n }\n throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);\n }\n }\n /**\n * Parses given command string into component array, splitting on spaces unless\n * spaces are between quotation marks.\n */\n static parseCommand(command) {\n // Split the command into components by splitting on spaces,\n // unless spaces are contained in quotation marks.\n const components = command.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g);\n if (!components) {\n throw new Error(`Provided command: \"${command}\" could not be parsed.`);\n }\n // Remove quotation marks from the beginning and end of each component if they are present.\n for (let i = 0; i < components.length; i++) {\n if (components[i][0] === '\"' && components[i].slice(-1) === '\"') {\n components[i] = components[i].slice(1, -1);\n }\n }\n return components;\n }\n}\nexports.PluggableAuthHandler = PluggableAuthHandler;\n//# sourceMappingURL=pluggable-auth-handler.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthClient = exports.ExecutableError = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst executable_response_1 = require(\"./executable-response\");\nconst pluggable_auth_handler_1 = require(\"./pluggable-auth-handler\");\nvar pluggable_auth_handler_2 = require(\"./pluggable-auth-handler\");\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_handler_2.ExecutableError; } });\n/**\n * The default executable timeout when none is provided, in milliseconds.\n */\nconst DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;\n/**\n * The minimum allowed executable timeout in milliseconds.\n */\nconst MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;\n/**\n * The maximum allowed executable timeout in milliseconds.\n */\nconst MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;\n/**\n * The environment variable to check to see if executable can be run.\n * Value must be set to '1' for the executable to run.\n */\nconst GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';\n/**\n * The maximum currently supported executable version.\n */\nconst MAXIMUM_EXECUTABLE_VERSION = 1;\n/**\n * PluggableAuthClient enables the exchange of workload identity pool external credentials for\n * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These\n * scripts/executables are completely independent of the Google Cloud Auth libraries. These\n * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token\n * to be exchanged for a Google access token.\n *\n *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable\n * must be set to '1'. This is for security reasons.\n *\n *

Both OIDC and SAML are supported. The executable must adhere to a specific response format\n * defined below.\n *\n *

The executable must print out the 3rd party token to STDOUT in JSON format. When an\n * output_file is specified in the credential configuration, the executable must also handle writing the\n * JSON response to this file.\n *\n *

\n * OIDC response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:id_token\",\n *   \"id_token\": \"HEADER.PAYLOAD.SIGNATURE\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * SAML2 response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:saml2\",\n *   \"saml_response\": \"...\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * Error response sample:\n * {\n *   \"version\": 1,\n *   \"success\": false,\n *   \"code\": \"401\",\n *   \"message\": \"Error message.\"\n * }\n * 
\n *\n *

The \"expiration_time\" field in the JSON response is only required for successful\n * responses when an output file was specified in the credential configuration\n *\n *

The auth libraries will populate certain environment variables that will be accessible by the\n * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,\n * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and\n * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.\n *\n *

Please see this repositories README for a complete executable request/response specification.\n */\nclass PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {\n /**\n * The command used to retrieve the third party token.\n */\n command;\n /**\n * The timeout in milliseconds for running executable,\n * set to default if none provided.\n */\n timeoutMillis;\n /**\n * The path to file to check for cached executable response.\n */\n outputFile;\n /**\n * Executable and output file handler.\n */\n handler;\n /**\n * Instantiates a PluggableAuthClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid pluggable auth credential.\n * @param options The external account options object typically loaded from\n * the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n if (!options.credential_source.executable) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n this.command = options.credential_source.executable.command;\n if (!this.command) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n // Check if the provided timeout exists and if it is valid.\n if (options.credential_source.executable.timeout_millis === undefined) {\n this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;\n }\n else {\n this.timeoutMillis = options.credential_source.executable.timeout_millis;\n if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||\n this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {\n throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +\n `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);\n }\n }\n this.outputFile = options.credential_source.executable.output_file;\n this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({\n command: this.command,\n timeoutMillis: this.timeoutMillis,\n outputFile: this.outputFile,\n });\n this.credentialSourceType = 'executable';\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint.\n * This uses the `options.credential_source` object to figure out how\n * to retrieve the token using the current environment. In this case,\n * this calls a user provided executable which returns the subject token.\n * The logic is summarized as:\n * 1. Validated that the executable is allowed to run. The\n * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to\n * 1 for security reasons.\n * 2. If an output file is specified by the user, check the file location\n * for a response. If the file exists and contains a valid response,\n * return the subject token from the file.\n * 3. Call the provided executable and return response.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Check if the executable is allowed to run.\n if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {\n throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +\n 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +\n 'Variable to 1.');\n }\n let executableResponse = undefined;\n // Try to get cached executable response from output file.\n if (this.outputFile) {\n executableResponse = await this.handler.retrieveCachedResponse();\n }\n // If no response from output file, call the executable.\n if (!executableResponse) {\n // Set up environment map with required values for the executable.\n const envMap = new Map();\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);\n // Always set to 0 because interactive mode is not supported.\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');\n if (this.outputFile) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);\n }\n const serviceAccountEmail = this.getServiceAccountEmail();\n if (serviceAccountEmail) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);\n }\n executableResponse =\n await this.handler.retrieveResponseFromExecutable(envMap);\n }\n if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {\n throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);\n }\n // Check that response was successful.\n if (!executableResponse.success) {\n throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);\n }\n // Check that response contains expiration time if output file was specified.\n if (this.outputFile) {\n if (!executableResponse.expirationTime) {\n throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');\n }\n }\n // Check that response is not expired.\n if (executableResponse.isExpired()) {\n throw new Error('Executable response is expired.');\n }\n // Return subject token from response.\n return executableResponse.subjectToken;\n }\n}\nexports.PluggableAuthClient = PluggableAuthClient;\n//# sourceMappingURL=pluggable-auth-client.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst identitypoolclient_1 = require(\"./identitypoolclient\");\nconst awsclient_1 = require(\"./awsclient\");\nconst pluggable_auth_client_1 = require(\"./pluggable-auth-client\");\n/**\n * Dummy class with no constructor. Developers are expected to use fromJSON.\n */\nclass ExternalAccountClient {\n constructor() {\n throw new Error('ExternalAccountClients should be initialized via: ' +\n 'ExternalAccountClient.fromJSON(), ' +\n 'directly via explicit constructors, eg. ' +\n 'new AwsClient(options), new IdentityPoolClient(options), new' +\n 'PluggableAuthClientOptions, or via ' +\n 'new GoogleAuth(options).getClient()');\n }\n /**\n * This static method will instantiate the\n * corresponding type of external account credential depending on the\n * underlying credential source.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n * @return A BaseExternalAccountClient instance or null if the options\n * provided do not correspond to an external account credential.\n */\n static fromJSON(options) {\n if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n if (options.credential_source?.environment_id) {\n return new awsclient_1.AwsClient(options);\n }\n else if (options.credential_source?.executable) {\n return new pluggable_auth_client_1.PluggableAuthClient(options);\n }\n else {\n return new identitypoolclient_1.IdentityPoolClient(options);\n }\n }\n else {\n return null;\n }\n }\n}\nexports.ExternalAccountClient = ExternalAccountClient;\n//# sourceMappingURL=externalclient.js.map", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0;\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\n/**\n * The credentials JSON file type for external account authorized user clients.\n */\nexports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken';\n/**\n * Handler for token refresh requests sent to the token_url endpoint for external\n * authorized user credentials.\n */\nclass ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {\n #tokenRefreshEndpoint;\n /**\n * Initializes an ExternalAccountAuthorizedUserHandler instance.\n * @param url The URL of the token refresh endpoint.\n * @param transporter The transporter to use for the refresh request.\n * @param clientAuthentication The client authentication credentials to use\n * for the refresh request.\n */\n constructor(options) {\n super(options);\n this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint;\n }\n /**\n * Requests a new access token from the token_url endpoint using the provided\n * refresh token.\n * @param refreshToken The refresh token to use to generate a new access token.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @return A promise that resolves with the token refresh response containing\n * the requested access token and its expiration time.\n */\n async refreshToken(refreshToken, headers) {\n const opts = {\n ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,\n url: this.#tokenRefreshEndpoint,\n method: 'POST',\n headers,\n data: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const tokenRefreshResponse = response.data;\n tokenRefreshResponse.res = response;\n return tokenRefreshResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\n/**\n * External Account Authorized User Client. This is used for OAuth2 credentials\n * sourced using external identities through Workforce Identity Federation.\n * Obtaining the initial access and refresh token can be done through the\n * Google Cloud CLI.\n */\nclass ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient {\n cachedAccessToken;\n externalAccountAuthorizedUserHandler;\n refreshToken;\n /**\n * Instantiates an ExternalAccountAuthorizedUserClient instances using the\n * provided JSON object loaded from a credentials files.\n * An error is throws if the credential is not valid.\n * @param options The external account authorized user option object typically\n * from the external accoutn authorized user JSON credential file.\n */\n constructor(options) {\n super(options);\n if (options.universe_domain) {\n this.universeDomain = options.universe_domain;\n }\n this.refreshToken = options.refresh_token;\n const clientAuthentication = {\n confidentialClientType: 'basic',\n clientId: options.client_id,\n clientSecret: options.client_secret,\n };\n this.externalAccountAuthorizedUserHandler =\n new ExternalAccountAuthorizedUserHandler({\n tokenRefreshEndpoint: options.token_url ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain),\n transporter: this.transporter,\n clientAuthentication,\n });\n this.cachedAccessToken = null;\n this.quotaProjectId = options.quota_project_id;\n // As threshold could be zero,\n // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the\n // zero value.\n if (typeof options?.eagerRefreshThresholdMillis !== 'number') {\n this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;\n }\n else {\n this.eagerRefreshThresholdMillis = options\n .eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure;\n }\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * @return A promise that resolves with the refreshed credential.\n */\n async refreshAccessTokenAsync() {\n // Refresh the access token using the refresh token.\n const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);\n this.cachedAccessToken = {\n access_token: refreshResponse.access_token,\n expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000,\n res: refreshResponse.res,\n };\n if (refreshResponse.refresh_token !== undefined) {\n this.refreshToken = refreshResponse.refresh_token;\n }\n return this.cachedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param credentials The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(credentials) {\n const now = new Date().getTime();\n return credentials.expiry_date\n ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;\n//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;\nconst child_process_1 = require(\"child_process\");\nconst fs = require(\"fs\");\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst computeclient_1 = require(\"./computeclient\");\nconst idtokenclient_1 = require(\"./idtokenclient\");\nconst envDetect_1 = require(\"./envDetect\");\nconst jwtclient_1 = require(\"./jwtclient\");\nconst refreshclient_1 = require(\"./refreshclient\");\nconst impersonated_1 = require(\"./impersonated\");\nconst externalclient_1 = require(\"./externalclient\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst authclient_1 = require(\"./authclient\");\nconst externalAccountAuthorizedUserClient_1 = require(\"./externalAccountAuthorizedUserClient\");\nconst util_1 = require(\"../util\");\nexports.GoogleAuthExceptionMessages = {\n API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.',\n NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.',\n NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\\n' +\n 'To learn more about Universe Domain retrieval, visit: \\n' +\n 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys',\n};\nclass GoogleAuth {\n /**\n * Caches a value indicating whether the auth layer is running on Google\n * Compute Engine.\n * @private\n */\n checkIsGCE = undefined;\n useJWTAccessWithScope;\n defaultServicePath;\n // Note: this properly is only public to satisfy unit tests.\n // https://github.com/Microsoft/TypeScript/issues/5228\n get isGCE() {\n return this.checkIsGCE;\n }\n _findProjectIdPromise;\n _cachedProjectId;\n // To save the contents of the JSON credential file\n jsonContent = null;\n apiKey;\n cachedCredential = null;\n /**\n * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.\n */\n #pendingAuthClient = null;\n /**\n * Scopes populated by the client library by default. We differentiate between\n * these and user defined scopes when deciding whether to use a self-signed JWT.\n */\n defaultScopes;\n keyFilename;\n scopes;\n clientOptions = {};\n /**\n * Configuration is resolved in the following order of precedence:\n * - {@link GoogleAuthOptions.credentials `credentials`}\n * - {@link GoogleAuthOptions.keyFilename `keyFilename`}\n * - {@link GoogleAuthOptions.keyFile `keyFile`}\n *\n * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the\n * {@link AuthClient `AuthClient`s}.\n *\n * @param opts\n */\n constructor(opts = {}) {\n this._cachedProjectId = opts.projectId || null;\n this.cachedCredential = opts.authClient || null;\n this.keyFilename = opts.keyFilename || opts.keyFile;\n this.scopes = opts.scopes;\n this.clientOptions = opts.clientOptions || {};\n this.jsonContent = opts.credentials || null;\n this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;\n // Cannot use both API Key + Credentials\n if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {\n throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);\n }\n if (opts.universeDomain) {\n this.clientOptions.universeDomain = opts.universeDomain;\n }\n }\n // GAPIC client libraries should always use self-signed JWTs. The following\n // variables are set on the JWT client in order to indicate the type of library,\n // and sign the JWT with the correct audience and scopes (if not supplied).\n setGapicJWTValues(client) {\n client.defaultServicePath = this.defaultServicePath;\n client.useJWTAccessWithScope = this.useJWTAccessWithScope;\n client.defaultScopes = this.defaultScopes;\n }\n getProjectId(callback) {\n if (callback) {\n this.getProjectIdAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getProjectIdAsync();\n }\n }\n /**\n * A temporary method for internal `getProjectId` usages where `null` is\n * acceptable. In a future major release, `getProjectId` should return `null`\n * (as the `Promise` base signature describes) and this private\n * method should be removed.\n *\n * @returns Promise that resolves with project id (or `null`)\n */\n async getProjectIdOptional() {\n try {\n return await this.getProjectId();\n }\n catch (e) {\n if (e instanceof Error &&\n e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {\n return null;\n }\n else {\n throw e;\n }\n }\n }\n /**\n * A private method for finding and caching a projectId.\n *\n * Supports environments in order of precedence:\n * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable\n * - GOOGLE_APPLICATION_CREDENTIALS JSON file\n * - Cloud SDK: `gcloud config config-helper --format json`\n * - GCE project ID from metadata server\n *\n * @returns projectId\n */\n async findAndCacheProjectId() {\n let projectId = null;\n projectId ||= await this.getProductionProjectId();\n projectId ||= await this.getFileProjectId();\n projectId ||= await this.getDefaultServiceProjectId();\n projectId ||= await this.getGCEProjectId();\n projectId ||= await this.getExternalAccountClientProjectId();\n if (projectId) {\n this._cachedProjectId = projectId;\n return projectId;\n }\n else {\n throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);\n }\n }\n async getProjectIdAsync() {\n if (this._cachedProjectId) {\n return this._cachedProjectId;\n }\n if (!this._findProjectIdPromise) {\n this._findProjectIdPromise = this.findAndCacheProjectId();\n }\n return this._findProjectIdPromise;\n }\n /**\n * Retrieves a universe domain from the metadata server via\n * {@link gcpMetadata.universe}.\n *\n * @returns a universe domain\n */\n async getUniverseDomainFromMetadataServer() {\n let universeDomain;\n try {\n universeDomain = await gcpMetadata.universe('universe-domain');\n universeDomain ||= authclient_1.DEFAULT_UNIVERSE;\n }\n catch (e) {\n if (e && e?.response?.status === 404) {\n universeDomain = authclient_1.DEFAULT_UNIVERSE;\n }\n else {\n throw e;\n }\n }\n return universeDomain;\n }\n /**\n * Retrieves, caches, and returns the universe domain in the following order\n * of precedence:\n * - The universe domain in {@link GoogleAuth.clientOptions}\n * - An existing or ADC {@link AuthClient}'s universe domain\n * - {@link gcpMetadata.universe}, if {@link Compute} client\n *\n * @returns The universe domain\n */\n async getUniverseDomain() {\n let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain');\n try {\n universeDomain ??= (await this.getClient()).universeDomain;\n }\n catch {\n // client or ADC is not available\n universeDomain ??= authclient_1.DEFAULT_UNIVERSE;\n }\n return universeDomain;\n }\n /**\n * @returns Any scopes (user-specified or default scopes specified by the\n * client library) that need to be set on the current Auth client.\n */\n getAnyScopes() {\n return this.scopes || this.defaultScopes;\n }\n getApplicationDefault(optionsOrCallback = {}, callback) {\n let options;\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);\n }\n else {\n return this.getApplicationDefaultAsync(options);\n }\n }\n async getApplicationDefaultAsync(options = {}) {\n // If we've already got a cached credential, return it.\n // This will also preserve one's configured quota project, in case they\n // set one directly on the credential previously.\n if (this.cachedCredential) {\n // cache, while preserving existing quota project preferences\n return await this.#prepareAndCacheClient(this.cachedCredential, null);\n }\n let credential;\n // Check for the existence of a local environment variable pointing to the\n // location of the credential file. This is typically used in local\n // developer scenarios.\n credential =\n await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Look in the well-known credential file location.\n credential =\n await this._tryGetApplicationCredentialsFromWellKnownFile(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Determine if we're running on GCE.\n if (await this._checkIsGCE()) {\n options.scopes = this.getAnyScopes();\n return await this.#prepareAndCacheClient(new computeclient_1.Compute(options));\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND);\n }\n async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) {\n const projectId = await this.getProjectIdOptional();\n if (quotaProjectIdOverride) {\n credential.quotaProjectId = quotaProjectIdOverride;\n }\n this.cachedCredential = credential;\n return { credential, projectId };\n }\n /**\n * Determines whether the auth layer is running on Google Compute Engine.\n * Checks for GCP Residency, then fallback to checking if metadata server\n * is available.\n *\n * @returns A promise that resolves with the boolean.\n * @api private\n */\n async _checkIsGCE() {\n if (this.checkIsGCE === undefined) {\n this.checkIsGCE =\n gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable());\n }\n return this.checkIsGCE;\n }\n /**\n * Attempts to load default credentials from the environment variable path..\n * @returns Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {\n const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||\n process.env['google_application_credentials'];\n if (!credentialsPath || credentialsPath.length === 0) {\n return null;\n }\n try {\n return this._getApplicationCredentialsFromFilePath(credentialsPath, options);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;\n }\n throw e;\n }\n }\n /**\n * Attempts to load default credentials from a well-known file location\n * @return Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromWellKnownFile(options) {\n // First, figure out the location of the file, depending upon the OS type.\n let location = null;\n if (this._isWindows()) {\n // Windows\n location = process.env['APPDATA'];\n }\n else {\n // Linux or Mac\n const home = process.env['HOME'];\n if (home) {\n location = path.join(home, '.config');\n }\n }\n // If we found the root path, expand it.\n if (location) {\n location = path.join(location, 'gcloud', 'application_default_credentials.json');\n if (!fs.existsSync(location)) {\n location = null;\n }\n }\n // The file does not exist.\n if (!location) {\n return null;\n }\n // The file seems to exist. Try to use it.\n const client = await this._getApplicationCredentialsFromFilePath(location, options);\n return client;\n }\n /**\n * Attempts to load default credentials from a file at the given path..\n * @param filePath The path to the file to read.\n * @returns Promise that resolves with the OAuth2Client\n * @api private\n */\n async _getApplicationCredentialsFromFilePath(filePath, options = {}) {\n // Make sure the path looks like a string.\n if (!filePath || filePath.length === 0) {\n throw new Error('The file path is invalid.');\n }\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n filePath = fs.realpathSync(filePath);\n if (!fs.lstatSync(filePath).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n // Now open a read stream on the file, and parse it.\n const readStream = fs.createReadStream(filePath);\n return this.fromStream(readStream, options);\n }\n /**\n * Create a credentials instance using a given impersonated input options.\n * @param json The impersonated input object.\n * @returns JWT or UserRefresh Client with data\n */\n fromImpersonatedJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing an impersonated refresh token');\n }\n if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n throw new Error(`The incoming JSON object does not have the \"${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}\" type`);\n }\n if (!json.source_credentials) {\n throw new Error('The incoming JSON object does not contain a source_credentials field');\n }\n if (!json.service_account_impersonation_url) {\n throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');\n }\n const sourceClient = this.fromJSON(json.source_credentials);\n if (json.service_account_impersonation_url?.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85}\n **/\n throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);\n }\n // Extract service account from service_account_impersonation_url\n const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;\n if (!targetPrincipal) {\n throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);\n }\n const targetScopes = this.getAnyScopes() ?? [];\n return new impersonated_1.Impersonated({\n ...json,\n sourceClient,\n targetPrincipal,\n targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],\n });\n }\n /**\n * Create a credentials instance using the given input options.\n * This client is not cached.\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n *\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n fromJSON(json, options = {}) {\n let client;\n // user's preferred universe domain\n const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {\n client = new refreshclient_1.UserRefreshClient(options);\n client.fromJSON(json);\n }\n else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n client = this.fromImpersonatedJSON(json);\n }\n else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n client = externalclient_1.ExternalAccountClient.fromJSON({\n ...json,\n ...options,\n });\n client.scopes = this.getAnyScopes();\n }\n else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {\n client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({\n ...json,\n ...options,\n });\n }\n else {\n options.scopes = this.scopes;\n client = new jwtclient_1.JWT(options);\n this.setGapicJWTValues(client);\n client.fromJSON(json);\n }\n if (preferredUniverseDomain) {\n client.universeDomain = preferredUniverseDomain;\n }\n return client;\n }\n /**\n * Return a JWT or UserRefreshClient from JavaScript object, caching both the\n * object used to instantiate and the client.\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n _cacheClientFromJSON(json, options) {\n const client = this.fromJSON(json, options);\n // cache both raw data used to instantiate client and client itself.\n this.jsonContent = json;\n this.cachedCredential = client;\n return client;\n }\n fromStream(inputStream, optionsOrCallback = {}, callback) {\n let options = {};\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);\n }\n else {\n return this.fromStreamAsync(inputStream, options);\n }\n }\n fromStreamAsync(inputStream, options) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the Google auth settings.');\n }\n const chunks = [];\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => chunks.push(chunk))\n .on('end', () => {\n try {\n try {\n const data = JSON.parse(chunks.join(''));\n const r = this._cacheClientFromJSON(data, options);\n return resolve(r);\n }\n catch (err) {\n // If we failed parsing this.keyFileName, assume that it\n // is a PEM or p12 certificate:\n if (!this.keyFilename)\n throw err;\n const client = new jwtclient_1.JWT({\n ...this.clientOptions,\n keyFile: this.keyFilename,\n });\n this.cachedCredential = client;\n this.setGapicJWTValues(client);\n return resolve(client);\n }\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a credentials instance using the given API key string.\n * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.\n *\n * @param apiKey The API key string\n * @param options An optional options object.\n * @returns A JWT loaded from the key\n */\n fromAPIKey(apiKey, options = {}) {\n return new jwtclient_1.JWT({ ...options, apiKey });\n }\n /**\n * Determines whether the current operating system is Windows.\n * @api private\n */\n _isWindows() {\n const sys = os.platform();\n if (sys && sys.length >= 3) {\n if (sys.substring(0, 3).toLowerCase() === 'win') {\n return true;\n }\n }\n return false;\n }\n /**\n * Run the Google Cloud SDK command that prints the default project ID\n */\n async getDefaultServiceProjectId() {\n return new Promise(resolve => {\n (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {\n if (!err && stdout) {\n try {\n const projectId = JSON.parse(stdout).configuration.properties.core.project;\n resolve(projectId);\n return;\n }\n catch (e) {\n // ignore errors\n }\n }\n resolve(null);\n });\n });\n }\n /**\n * Loads the project id from environment variables.\n * @api private\n */\n getProductionProjectId() {\n return (process.env['GCLOUD_PROJECT'] ||\n process.env['GOOGLE_CLOUD_PROJECT'] ||\n process.env['gcloud_project'] ||\n process.env['google_cloud_project']);\n }\n /**\n * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.\n * @api private\n */\n async getFileProjectId() {\n if (this.cachedCredential) {\n // Try to read the project ID from the cached credentials file\n return this.cachedCredential.projectId;\n }\n // Ensure the projectId is loaded from the keyFile if available.\n if (this.keyFilename) {\n const creds = await this.getClient();\n if (creds && creds.projectId) {\n return creds.projectId;\n }\n }\n // Try to load a credentials file and read its project ID\n const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();\n if (r) {\n return r.projectId;\n }\n else {\n return null;\n }\n }\n /**\n * Gets the project ID from external account client if available.\n */\n async getExternalAccountClientProjectId() {\n if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n return null;\n }\n const creds = await this.getClient();\n // Do not suppress the underlying error, as the error could contain helpful\n // information for debugging and fixing. This is especially true for\n // external account creds as in order to get the project ID, the following\n // operations have to succeed:\n // 1. Valid credentials file should be supplied.\n // 2. Ability to retrieve access tokens from STS token exchange API.\n // 3. Ability to exchange for service account impersonated credentials (if\n // enabled).\n // 4. Ability to get project info using the access token from step 2 or 3.\n // Without surfacing the error, it is harder for developers to determine\n // which step went wrong.\n return await creds.getProjectId();\n }\n /**\n * Gets the Compute Engine project ID if it can be inferred.\n */\n async getGCEProjectId() {\n try {\n const r = await gcpMetadata.project('project-id');\n return r;\n }\n catch (e) {\n // Ignore any errors\n return null;\n }\n }\n getCredentials(callback) {\n if (callback) {\n this.getCredentialsAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getCredentialsAsync();\n }\n }\n async getCredentialsAsync() {\n const client = await this.getClient();\n if (client instanceof impersonated_1.Impersonated) {\n return { client_email: client.getTargetPrincipal() };\n }\n if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {\n const serviceAccountEmail = client.getServiceAccountEmail();\n if (serviceAccountEmail) {\n return {\n client_email: serviceAccountEmail,\n universe_domain: client.universeDomain,\n };\n }\n }\n if (this.jsonContent) {\n return {\n client_email: this.jsonContent.client_email,\n private_key: this.jsonContent.private_key,\n universe_domain: this.jsonContent.universe_domain,\n };\n }\n if (await this._checkIsGCE()) {\n const [client_email, universe_domain] = await Promise.all([\n gcpMetadata.instance('service-accounts/default/email'),\n this.getUniverseDomain(),\n ]);\n return { client_email, universe_domain };\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);\n }\n /**\n * Automatically obtain an {@link AuthClient `AuthClient`} based on the\n * provided configuration. If no options were passed, use Application\n * Default Credentials.\n */\n async getClient() {\n if (this.cachedCredential) {\n return this.cachedCredential;\n }\n // Use an existing auth client request, or cache a new one\n this.#pendingAuthClient =\n this.#pendingAuthClient || this.#determineClient();\n try {\n return await this.#pendingAuthClient;\n }\n finally {\n // reset the pending auth client in case it is changed later\n this.#pendingAuthClient = null;\n }\n }\n async #determineClient() {\n if (this.jsonContent) {\n return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);\n }\n else if (this.keyFilename) {\n const filePath = path.resolve(this.keyFilename);\n const stream = fs.createReadStream(filePath);\n return await this.fromStreamAsync(stream, this.clientOptions);\n }\n else if (this.apiKey) {\n const client = await this.fromAPIKey(this.apiKey, this.clientOptions);\n client.scopes = this.scopes;\n const { credential } = await this.#prepareAndCacheClient(client);\n return credential;\n }\n else {\n const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);\n return credential;\n }\n }\n /**\n * Creates a client which will fetch an ID token for authorization.\n * @param targetAudience the audience for the fetched ID token.\n * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.\n */\n async getIdTokenClient(targetAudience) {\n const client = await this.getClient();\n if (!('fetchIdToken' in client)) {\n throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');\n }\n return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });\n }\n /**\n * Automatically obtain application default credentials, and return\n * an access token for making requests.\n */\n async getAccessToken() {\n const client = await this.getClient();\n return (await client.getAccessToken()).token;\n }\n /**\n * Obtain the HTTP headers that will provide authorization for a given\n * request.\n */\n async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }\n /**\n * Obtain credentials for a request, then attach the appropriate headers to\n * the request options.\n * @param opts Axios or Request options on which to attach the headers\n */\n async authorizeRequest(opts = {}) {\n const url = opts.url;\n const client = await this.getClient();\n const headers = await client.getRequestHeaders(url);\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);\n return opts;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.\n *\n * @see {@link GoogleAuth.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const auth = new GoogleAuth();\n * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);\n * await fetchWithAuth('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n async fetch(...args) {\n const client = await this.getClient();\n return client.fetch(...args);\n }\n /**\n * Automatically obtain application default credentials, and make an\n * HTTP request using the given options.\n *\n * @see {@link GoogleAuth.fetch} for the modern method.\n *\n * @param opts Axios request options for the HTTP request.\n */\n async request(opts) {\n const client = await this.getClient();\n return client.request(opts);\n }\n /**\n * Determine the compute environment in which the code is running.\n */\n getEnv() {\n return (0, envDetect_1.getEnv)();\n }\n /**\n * Sign the given data with the current private key, or go out\n * to the IAM API to sign it.\n * @param data The data to be signed.\n * @param endpoint A custom endpoint to use.\n *\n * @example\n * ```\n * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');\n * ```\n */\n async sign(data, endpoint) {\n const client = await this.getClient();\n const universe = await this.getUniverseDomain();\n endpoint =\n endpoint ||\n `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;\n if (client instanceof impersonated_1.Impersonated) {\n const signed = await client.sign(data);\n return signed.signedBlob;\n }\n const crypto = (0, crypto_1.createCrypto)();\n if (client instanceof jwtclient_1.JWT && client.key) {\n const sign = await crypto.sign(client.key, data);\n return sign;\n }\n const creds = await this.getCredentials();\n if (!creds.client_email) {\n throw new Error('Cannot sign data without `client_email`.');\n }\n return this.signBlob(crypto, creds.client_email, data, endpoint);\n }\n async signBlob(crypto, emailOrUniqueId, data, endpoint) {\n const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`);\n const res = await this.request({\n method: 'POST',\n url: url.href,\n data: {\n payload: crypto.encodeBase64StringUtf8(data),\n },\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['POST'],\n },\n });\n return res.data.signedBlob;\n }\n}\nexports.GoogleAuth = GoogleAuth;\n//# sourceMappingURL=googleauth.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IAMAuth = void 0;\nclass IAMAuth {\n selector;\n token;\n /**\n * IAM credentials.\n *\n * @param selector the iam authority selector\n * @param token the token\n * @constructor\n */\n constructor(selector, token) {\n this.selector = selector;\n this.token = token;\n this.selector = selector;\n this.token = token;\n }\n /**\n * Acquire the HTTP headers required to make an authenticated request.\n */\n getRequestHeaders() {\n return {\n 'x-goog-iam-authority-selector': this.selector,\n 'x-goog-iam-authorization-token': this.token,\n };\n }\n}\nexports.IAMAuth = IAMAuth;\n//# sourceMappingURL=iam.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The requested token exchange subject_token_type: rfc8693#section-2.1\n */\nconst STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The maximum number of access boundary rules a Credential Access Boundary\n * can contain.\n */\nexports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * Defines a set of Google credentials that are downscoped from an existing set\n * of Google OAuth2 credentials. This is useful to restrict the Identity and\n * Access Management (IAM) permissions that a short-lived credential can use.\n * The common pattern of usage is to have a token broker with elevated access\n * generate these downscoped credentials from higher access source credentials\n * and pass the downscoped short-lived access tokens to a token consumer via\n * some secure authenticated channel for limited access to Google Cloud Storage\n * resources.\n */\nclass DownscopedClient extends authclient_1.AuthClient {\n authClient;\n credentialAccessBoundary;\n cachedDownscopedAccessToken;\n stsCredential;\n /**\n * Instantiates a downscoped client object using the provided source\n * AuthClient and credential access boundary rules.\n * To downscope permissions of a source AuthClient, a Credential Access\n * Boundary that specifies which resources the new credential can access, as\n * well as an upper bound on the permissions that are available on each\n * resource, has to be defined. A downscoped client can then be instantiated\n * using the source AuthClient and the Credential Access Boundary.\n * @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.\n * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.\n */\n constructor(\n /**\n * AuthClient is for backwards-compatibility.\n */\n options, \n /**\n * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead\n */\n credentialAccessBoundary = {\n accessBoundary: {\n accessBoundaryRules: [],\n },\n }) {\n super(options instanceof authclient_1.AuthClient ? {} : options);\n if (options instanceof authclient_1.AuthClient) {\n this.authClient = options;\n this.credentialAccessBoundary = credentialAccessBoundary;\n }\n else {\n this.authClient = options.authClient;\n this.credentialAccessBoundary = options.credentialAccessBoundary;\n }\n // Check 1-10 Access Boundary Rules are defined within Credential Access\n // Boundary.\n if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules\n .length === 0) {\n throw new Error('At least one access boundary rule needs to be defined.');\n }\n else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >\n exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {\n throw new Error('The provided access boundary has more than ' +\n `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);\n }\n // Check at least one permission should be defined in each Access Boundary\n // Rule.\n for (const rule of this.credentialAccessBoundary.accessBoundary\n .accessBoundaryRules) {\n if (rule.availablePermissions.length === 0) {\n throw new Error('At least one permission should be defined in access boundary rules.');\n }\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token`,\n });\n this.cachedDownscopedAccessToken = null;\n }\n /**\n * Provides a mechanism to inject Downscoped access tokens directly.\n * The expiry_date field is required to facilitate determination of the token\n * expiration which would make it easier for the token consumer to handle.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n if (!credentials.expiry_date) {\n throw new Error('The access token expiry_date field is missing in the provided ' +\n 'credentials.');\n }\n super.setCredentials(credentials);\n this.cachedDownscopedAccessToken = credentials;\n }\n async getAccessToken() {\n // If the cached access token is unavailable or expired, force refresh.\n // The Downscoped access token will be returned in\n // DownscopedAccessTokenResponse format.\n if (!this.cachedDownscopedAccessToken ||\n this.isExpired(this.cachedDownscopedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return Downscoped access token in DownscopedAccessTokenResponse format.\n return {\n token: this.cachedDownscopedAccessToken.access_token,\n expirationTime: this.cachedDownscopedAccessToken.expiry_date,\n res: this.cachedDownscopedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * GCP access tokens are retrieved from authclient object/source credential.\n * Then GCP access tokens are exchanged for downscoped access tokens via the\n * token exchange endpoint.\n * @return A promise that resolves with the fresh downscoped access token.\n */\n async refreshAccessTokenAsync() {\n // Retrieve GCP access token from source credential.\n const subjectToken = (await this.authClient.getAccessToken()).token;\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken: subjectToken,\n subjectTokenType: STS_SUBJECT_TOKEN_TYPE,\n };\n // Exchange the source AuthClient access token for a Downscoped access\n // token.\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);\n /**\n * The STS endpoint will only return the expiration time for the downscoped\n * access token if the original access token represents a service account.\n * The downscoped token's expiration time will always match the source\n * credential expiration. When no expires_in is returned, we can copy the\n * source credential's expiration time.\n */\n const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null;\n const expiryDate = stsResponse.expires_in\n ? new Date().getTime() + stsResponse.expires_in * 1000\n : sourceCredExpireDate;\n // Save response in cached access token.\n this.cachedDownscopedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: expiryDate,\n res: stsResponse.res,\n };\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedDownscopedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedDownscopedAccessToken.expiry_date,\n access_token: this.cachedDownscopedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedDownscopedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param downscopedAccessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(downscopedAccessToken) {\n const now = new Date().getTime();\n return downscopedAccessToken.expiry_date\n ? now >=\n downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.DownscopedClient = DownscopedClient;\n//# sourceMappingURL=downscopedclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PassThroughClient = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * An AuthClient without any Authentication information. Useful for:\n * - Anonymous access\n * - Local Emulators\n * - Testing Environments\n *\n */\nclass PassThroughClient extends authclient_1.AuthClient {\n /**\n * Creates a request without any authentication headers or checks.\n *\n * @remarks\n *\n * In testing environments it may be useful to change the provided\n * {@link AuthClient.transporter} for any desired request overrides/handling.\n *\n * @param opts\n * @returns The response of the request.\n */\n async request(opts) {\n return this.transporter.request(opts);\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getAccessToken() {\n return {};\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getRequestHeaders() {\n return new Headers();\n }\n}\nexports.PassThroughClient = PassThroughClient;\n//# sourceMappingURL=passthrough.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0;\n// Copyright 2017 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst googleauth_1 = require(\"./auth/googleauth\");\nObject.defineProperty(exports, \"GoogleAuth\", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });\n// Export common deps to ensure types/instances are the exact match. Useful\n// for consistently configuring the library across versions.\nexports.gcpMetadata = require(\"gcp-metadata\");\nexports.gaxios = require(\"gaxios\");\nvar authclient_1 = require(\"./auth/authclient\");\nObject.defineProperty(exports, \"AuthClient\", { enumerable: true, get: function () { return authclient_1.AuthClient; } });\nObject.defineProperty(exports, \"DEFAULT_UNIVERSE\", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } });\nvar computeclient_1 = require(\"./auth/computeclient\");\nObject.defineProperty(exports, \"Compute\", { enumerable: true, get: function () { return computeclient_1.Compute; } });\nvar envDetect_1 = require(\"./auth/envDetect\");\nObject.defineProperty(exports, \"GCPEnv\", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });\nvar iam_1 = require(\"./auth/iam\");\nObject.defineProperty(exports, \"IAMAuth\", { enumerable: true, get: function () { return iam_1.IAMAuth; } });\nvar idtokenclient_1 = require(\"./auth/idtokenclient\");\nObject.defineProperty(exports, \"IdTokenClient\", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } });\nvar jwtaccess_1 = require(\"./auth/jwtaccess\");\nObject.defineProperty(exports, \"JWTAccess\", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });\nvar jwtclient_1 = require(\"./auth/jwtclient\");\nObject.defineProperty(exports, \"JWT\", { enumerable: true, get: function () { return jwtclient_1.JWT; } });\nvar impersonated_1 = require(\"./auth/impersonated\");\nObject.defineProperty(exports, \"Impersonated\", { enumerable: true, get: function () { return impersonated_1.Impersonated; } });\nvar oauth2client_1 = require(\"./auth/oauth2client\");\nObject.defineProperty(exports, \"CodeChallengeMethod\", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } });\nObject.defineProperty(exports, \"OAuth2Client\", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } });\nObject.defineProperty(exports, \"ClientAuthentication\", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } });\nvar loginticket_1 = require(\"./auth/loginticket\");\nObject.defineProperty(exports, \"LoginTicket\", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });\nvar refreshclient_1 = require(\"./auth/refreshclient\");\nObject.defineProperty(exports, \"UserRefreshClient\", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });\nvar awsclient_1 = require(\"./auth/awsclient\");\nObject.defineProperty(exports, \"AwsClient\", { enumerable: true, get: function () { return awsclient_1.AwsClient; } });\nvar awsrequestsigner_1 = require(\"./auth/awsrequestsigner\");\nObject.defineProperty(exports, \"AwsRequestSigner\", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } });\nvar identitypoolclient_1 = require(\"./auth/identitypoolclient\");\nObject.defineProperty(exports, \"IdentityPoolClient\", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } });\nvar externalclient_1 = require(\"./auth/externalclient\");\nObject.defineProperty(exports, \"ExternalAccountClient\", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } });\nvar baseexternalclient_1 = require(\"./auth/baseexternalclient\");\nObject.defineProperty(exports, \"BaseExternalAccountClient\", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } });\nvar downscopedclient_1 = require(\"./auth/downscopedclient\");\nObject.defineProperty(exports, \"DownscopedClient\", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } });\nvar pluggable_auth_client_1 = require(\"./auth/pluggable-auth-client\");\nObject.defineProperty(exports, \"PluggableAuthClient\", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } });\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } });\nvar passthrough_1 = require(\"./auth/passthrough\");\nObject.defineProperty(exports, \"PassThroughClient\", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } });\nconst auth = new googleauth_1.GoogleAuth();\nexports.auth = auth;\n//# sourceMappingURL=index.js.map", "import Fastify, {\n FastifyInstance,\n FastifyReply,\n FastifyRequest,\n FastifyPluginAsync,\n FastifyPluginCallback,\n FastifyPluginOptions,\n FastifyRegisterOptions,\n preHandlerHookHandler,\n onRequestHookHandler,\n preParsingHookHandler,\n preValidationHookHandler,\n preSerializationHookHandler,\n onSendHookHandler,\n onResponseHookHandler,\n onTimeoutHookHandler,\n onErrorHookHandler,\n onRouteHookHandler,\n onRegisterHookHandler,\n onReadyHookHandler,\n onListenHookHandler,\n onCloseHookHandler,\n FastifyBaseLogger,\n FastifyLoggerOptions,\n} from \"fastify\";\nimport cors from \"@fastify/cors\";\nimport { ConfigService, AppConfig } from \"./services/config\";\nimport { errorHandler } from \"./api/middleware\";\nimport { registerApiRoutes } from \"./api/routes\";\nimport { LLMService } from \"./services/llm\";\nimport { ProviderService } from \"./services/provider\";\nimport { TransformerService } from \"./services/transformer\";\nimport { PinoLoggerOptions } from \"fastify/types/logger\";\n\n// Extend FastifyRequest to include custom properties\ndeclare module \"fastify\" {\n interface FastifyRequest {\n provider?: string;\n }\n interface FastifyInstance {\n _server?: Server;\n }\n}\n\ninterface ServerOptions {\n initialConfig?: AppConfig;\n logger?: boolean | PinoLoggerOptions;\n}\n\n// Application factory\nfunction createApp(logger: boolean | PinoLoggerOptions): FastifyInstance {\n const fastify = Fastify({\n bodyLimit: 50 * 1024 * 1024,\n logger,\n });\n\n // Register error handler\n fastify.setErrorHandler(errorHandler);\n\n // Register CORS\n fastify.register(cors);\n return fastify;\n}\n\n// Server class\nclass Server {\n private app: FastifyInstance;\n configService: ConfigService;\n llmService: LLMService;\n providerService: ProviderService;\n transformerService: TransformerService;\n\n constructor(options: ServerOptions = {}) {\n this.app = createApp(options.logger ?? true);\n this.configService = new ConfigService(options);\n this.transformerService = new TransformerService(\n this.configService,\n this.app.log\n );\n this.transformerService.initialize().finally(() => {\n this.providerService = new ProviderService(\n this.configService,\n this.transformerService,\n this.app.log\n );\n this.llmService = new LLMService(this.providerService);\n });\n }\n\n // Type-safe register method using Fastify native types\n async register(\n plugin: FastifyPluginAsync | FastifyPluginCallback,\n options?: FastifyRegisterOptions\n ): Promise {\n await (this.app as any).register(plugin, options);\n }\n\n // Type-safe addHook method with Fastify native types\n addHook(hookName: \"onRequest\", hookFunction: onRequestHookHandler): void;\n addHook(hookName: \"preParsing\", hookFunction: preParsingHookHandler): void;\n addHook(\n hookName: \"preValidation\",\n hookFunction: preValidationHookHandler\n ): void;\n addHook(hookName: \"preHandler\", hookFunction: preHandlerHookHandler): void;\n addHook(\n hookName: \"preSerialization\",\n hookFunction: preSerializationHookHandler\n ): void;\n addHook(hookName: \"onSend\", hookFunction: onSendHookHandler): void;\n addHook(hookName: \"onResponse\", hookFunction: onResponseHookHandler): void;\n addHook(hookName: \"onTimeout\", hookFunction: onTimeoutHookHandler): void;\n addHook(hookName: \"onError\", hookFunction: onErrorHookHandler): void;\n addHook(hookName: \"onRoute\", hookFunction: onRouteHookHandler): void;\n addHook(hookName: \"onRegister\", hookFunction: onRegisterHookHandler): void;\n addHook(hookName: \"onReady\", hookFunction: onReadyHookHandler): void;\n addHook(hookName: \"onListen\", hookFunction: onListenHookHandler): void;\n addHook(hookName: \"onClose\", hookFunction: onCloseHookHandler): void;\n public addHook(hookName: string, hookFunction: any): void {\n this.app.addHook(hookName as any, hookFunction);\n }\n\n async start(): Promise {\n try {\n this.app._server = this;\n\n this.app.addHook(\"preHandler\", (request, reply, done) => {\n if (request.url.startsWith('/v1/messages') && request.body) {\n request.log.info({ body: request.body }, \"request body\");\n request.body.stream === true\n if(!request.body.stream) {\n request.body.stream = false; // Ensure stream is false if not set\n }\n }\n done();\n });\n\n this.app.addHook(\n \"preHandler\",\n async (req: FastifyRequest, reply: FastifyReply) => {\n if (req.url.startsWith(\"/api\") || req.method !== \"POST\") return;\n try {\n const body = req.body as any;\n if (!body || !body.model) {\n return reply\n .code(400)\n .send({ error: \"Missing model in request body\" });\n }\n const [provider, model] = body.model.split(\",\");\n body.model = model;\n req.provider = provider;\n return;\n } catch (err) {\n req.log.error(\"Error in modelProviderMiddleware:\", err);\n return reply.code(500).send({ error: \"Internal server error\" });\n }\n }\n );\n\n this.app.register(registerApiRoutes);\n\n const address = await this.app.listen({\n port: parseInt(this.configService.get(\"PORT\") || \"3000\", 10),\n host: this.configService.get(\"HOST\") || \"127.0.0.1\",\n });\n\n this.app.log.info(`\uD83D\uDE80 LLMs API server listening on ${address}`);\n\n const shutdown = async (signal: string) => {\n this.app.log.info(`Received ${signal}, shutting down gracefully...`);\n await this.app.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n } catch (error) {\n this.app.log.error(`Error starting server: ${error}`);\n process.exit(1);\n }\n }\n}\n\n// Export for external use\nexport default Server;\n", "import { readFileSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { config } from \"dotenv\";\nimport JSON5 from 'json5';\n\nexport interface ConfigOptions {\n envPath?: string;\n jsonPath?: string;\n useEnvFile?: boolean;\n useJsonFile?: boolean;\n useEnvironmentVariables?: boolean;\n initialConfig?: AppConfig;\n}\n\nexport interface AppConfig {\n [key: string]: any;\n}\n\nexport class ConfigService {\n private config: AppConfig = {};\n private options: ConfigOptions;\n\n constructor(\n options: ConfigOptions = {\n jsonPath: \"./config.json\",\n }\n ) {\n this.options = {\n envPath: options.envPath || \".env\",\n jsonPath: options.jsonPath,\n useEnvFile: false,\n useJsonFile: options.useJsonFile !== false,\n useEnvironmentVariables: options.useEnvironmentVariables !== false,\n ...options,\n };\n\n this.loadConfig();\n }\n\n private loadConfig(): void {\n if (this.options.useJsonFile && this.options.jsonPath) {\n this.loadJsonConfig();\n }\n\n if (this.options.initialConfig) {\n this.config = { ...this.config, ...this.options.initialConfig };\n }\n\n if (this.options.useEnvFile) {\n this.loadEnvConfig();\n }\n\n // if (this.options.useEnvironmentVariables) {\n // this.loadEnvironmentVariables();\n // }\n\n if (this.config.LOG_FILE) {\n process.env.LOG_FILE = this.config.LOG_FILE;\n }\n if (this.config.LOG) {\n process.env.LOG = this.config.LOG;\n }\n }\n\n private loadJsonConfig(): void {\n if (!this.options.jsonPath) return;\n\n const jsonPath = this.isAbsolutePath(this.options.jsonPath)\n ? this.options.jsonPath\n : join(process.cwd(), this.options.jsonPath);\n\n if (existsSync(jsonPath)) {\n try {\n const jsonContent = readFileSync(jsonPath, \"utf-8\");\n const jsonConfig = JSON5.parse(jsonContent);\n this.config = { ...this.config, ...jsonConfig };\n console.log(`Loaded JSON config from: ${jsonPath}`);\n } catch (error) {\n console.warn(`Failed to load JSON config from ${jsonPath}:`, error);\n }\n } else {\n console.warn(`JSON config file not found: ${jsonPath}`);\n }\n }\n\n private loadEnvConfig(): void {\n const envPath = this.isAbsolutePath(this.options.envPath!)\n ? this.options.envPath!\n : join(process.cwd(), this.options.envPath!);\n\n if (existsSync(envPath)) {\n try {\n const result = config({ path: envPath });\n if (result.parsed) {\n this.config = {\n ...this.config,\n ...this.parseEnvConfig(result.parsed),\n };\n }\n } catch (error) {\n console.warn(`Failed to load .env config from ${envPath}:`, error);\n }\n }\n }\n\n private loadEnvironmentVariables(): void {\n const envConfig = this.parseEnvConfig(process.env);\n this.config = { ...this.config, ...envConfig };\n }\n\n private parseEnvConfig(\n env: Record\n ): Partial {\n const parsed: Partial = {};\n\n Object.assign(parsed, env);\n\n return parsed;\n }\n\n private isAbsolutePath(path: string): boolean {\n return path.startsWith(\"/\") || path.includes(\":\");\n }\n\n public get(key: keyof AppConfig): T | undefined;\n public get(key: keyof AppConfig, defaultValue: T): T;\n public get(key: keyof AppConfig, defaultValue?: T): T | undefined {\n const value = this.config[key];\n return value !== undefined ? (value as T) : defaultValue;\n }\n\n public getAll(): AppConfig {\n return { ...this.config };\n }\n\n public getHttpsProxy(): string | undefined {\n return (\n this.get(\"HTTPS_PROXY\") ||\n this.get(\"https_proxy\") ||\n this.get(\"httpsProxy\") ||\n this.get(\"PROXY_URL\")\n );\n }\n\n public has(key: keyof AppConfig): boolean {\n return this.config[key] !== undefined;\n }\n\n public set(key: keyof AppConfig, value: any): void {\n this.config[key] = value;\n }\n\n public reload(): void {\n this.config = {};\n this.loadConfig();\n }\n\n public getConfigSummary(): string {\n const summary: string[] = [];\n\n if (this.options.initialConfig) {\n summary.push(\"Initial Config\");\n }\n\n if (this.options.useJsonFile && this.options.jsonPath) {\n summary.push(`JSON: ${this.options.jsonPath}`);\n }\n\n if (this.options.useEnvFile) {\n summary.push(`ENV: ${this.options.envPath}`);\n }\n\n if (this.options.useEnvironmentVariables) {\n summary.push(\"Environment Variables\");\n }\n\n return `Config sources: ${summary.join(\", \")}`;\n }\n}\n", "import { FastifyRequest, FastifyReply } from \"fastify\";\n\nexport interface ApiError extends Error {\n statusCode?: number;\n code?: string;\n type?: string;\n}\n\nexport function createApiError(\n message: string,\n statusCode: number = 500,\n code: string = \"internal_error\",\n type: string = \"api_error\"\n): ApiError {\n const error = new Error(message) as ApiError;\n error.statusCode = statusCode;\n error.code = code;\n error.type = type;\n return error;\n}\n\nexport async function errorHandler(\n error: ApiError,\n request: FastifyRequest,\n reply: FastifyReply\n) {\n request.log.error(error);\n\n const statusCode = error.statusCode || 500;\n const response = {\n error: {\n message: error.message + error.stack || \"Internal Server Error\",\n type: error.type || \"api_error\",\n code: error.code || \"internal_error\",\n },\n };\n\n return reply.code(statusCode).send(response);\n}\n", "import { ProxyAgent } from \"undici\";\nimport { UnifiedChatRequest } from \"../types/llm\";\n\nexport function sendUnifiedRequest(\n url: URL | string,\n request: UnifiedChatRequest,\n config: any,\n logger?: any\n): Promise {\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n });\n if (config.headers) {\n Object.entries(config.headers).forEach(([key, value]) => {\n if (value) {\n headers.set(key, value as string);\n }\n });\n }\n let combinedSignal: AbortSignal;\n const timeoutSignal = AbortSignal.timeout(config.TIMEOUT ?? 60 * 1000 * 60);\n\n if (config.signal) {\n const controller = new AbortController();\n const abortHandler = () => controller.abort();\n config.signal.addEventListener(\"abort\", abortHandler);\n timeoutSignal.addEventListener(\"abort\", abortHandler);\n combinedSignal = controller.signal;\n } else {\n combinedSignal = timeoutSignal;\n }\n\n const fetchOptions: RequestInit = {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(request),\n signal: combinedSignal,\n };\n\n if (config.httpsProxy) {\n (fetchOptions as any).dispatcher = new ProxyAgent(\n new URL(config.httpsProxy).toString()\n );\n }\n logger?.debug(\n {\n request: fetchOptions,\n headers: Object.fromEntries(headers.entries()),\n requestUrl: typeof url === \"string\" ? url : url.toString(),\n useProxy: config.httpsProxy,\n },\n \"final request\"\n );\n return fetch(typeof url === \"string\" ? url : url.toString(), fetchOptions);\n}\n", "{\n \"name\": \"@musistudio/llms\",\n \"version\": \"1.0.28\",\n \"description\": \"A universal LLM API transformation server\",\n \"main\": \"dist/cjs/server.cjs\",\n \"module\": \"dist/esm/server.mjs\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/esm/server.mjs\",\n \"require\": \"./dist/cjs/server.cjs\"\n }\n },\n \"scripts\": {\n \"tsx\": \"tsx\",\n \"build\": \"tsx scripts/build.ts\",\n \"build:watch\": \"tsx scripts/build.ts --watch\",\n \"dev\": \"nodemon\",\n \"start\": \"node dist/cjs/server.cjs\",\n \"start:esm\": \"node dist/esm/server.mjs\",\n \"lint\": \"eslint src --ext .ts,.tsx\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.54.0\",\n \"@fastify/cors\": \"^11.0.1\",\n \"@google/genai\": \"^1.7.0\",\n \"dotenv\": \"^16.5.0\",\n \"fastify\": \"^5.4.0\",\n \"google-auth-library\": \"^10.1.0\",\n \"json5\": \"^2.2.3\",\n \"jsonrepair\": \"^3.13.0\",\n \"openai\": \"^5.6.0\",\n \"undici\": \"^7.10.0\",\n \"uuid\": \"^11.1.0\"\n },\n \"devDependencies\": {\n \"@types/chai\": \"^5.2.2\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/node\": \"^24.0.3\",\n \"@types/sinon\": \"^17.0.4\",\n \"@typescript-eslint/eslint-plugin\": \"^8.35.0\",\n \"@typescript-eslint/parser\": \"^8.35.0\",\n \"chai\": \"^5.2.0\",\n \"esbuild\": \"^0.25.5\",\n \"eslint\": \"^9.30.0\",\n \"nodemon\": \"^3.1.10\",\n \"sinon\": \"^21.0.0\",\n \"tsx\": \"^4.20.3\",\n \"typescript\": \"^5.8.3\",\n \"typescript-eslint\": \"^8.35.0\"\n }\n}\n", "import {\n FastifyInstance,\n FastifyPluginAsync,\n FastifyRequest,\n FastifyReply,\n} from \"fastify\";\nimport { RegisterProviderRequest, LLMProvider } from \"@/types/llm\";\nimport { sendUnifiedRequest } from \"@/utils/request\";\nimport { createApiError } from \"./middleware\";\nimport { version } from \"../../package.json\";\n\n/**\n * \u5904\u7406transformer\u7AEF\u70B9\u7684\u4E3B\u51FD\u6570\n * \u534F\u8C03\u6574\u4E2A\u8BF7\u6C42\u5904\u7406\u6D41\u7A0B\uFF1A\u9A8C\u8BC1\u63D0\u4F9B\u8005\u3001\u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u3001\u53D1\u9001\u8BF7\u6C42\u3001\u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u3001\u683C\u5F0F\u5316\u54CD\u5E94\n */\nasync function handleTransformerEndpoint(\n req: FastifyRequest,\n reply: FastifyReply,\n fastify: FastifyInstance,\n transformer: any\n) {\n const body = req.body as any;\n const providerName = req.provider!;\n const provider = fastify._server!.providerService.getProvider(providerName);\n\n // \u9A8C\u8BC1\u63D0\u4F9B\u8005\u662F\u5426\u5B58\u5728\n if (!provider) {\n throw createApiError(\n `Provider '${providerName}' not found`,\n 404,\n \"provider_not_found\"\n );\n }\n\n // \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n const { requestBody, config, bypass } = await processRequestTransformers(\n body,\n provider,\n transformer,\n req.headers\n );\n\n // \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n const response = await sendRequestToProvider(\n requestBody,\n config,\n provider,\n fastify,\n bypass,\n transformer\n );\n\n // \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n const finalResponse = await processResponseTransformers(\n requestBody,\n response,\n provider,\n transformer,\n bypass\n );\n\n // \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n return formatResponse(finalResponse, reply, body);\n}\n\n/**\n * \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884CtransformRequestOut\u3001provider transformers\u3001model-specific transformers\n * \u8FD4\u56DE\u5904\u7406\u540E\u7684\u8BF7\u6C42\u4F53\u3001\u914D\u7F6E\u548C\u662F\u5426\u8DF3\u8FC7\u8F6C\u6362\u5668\u7684\u6807\u5FD7\n */\nasync function processRequestTransformers(\n body: any,\n provider: any,\n transformer: any,\n headers: any\n) {\n let requestBody = body;\n let config = {};\n let bypass = false;\n\n // \u68C0\u67E5\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n bypass = shouldBypassTransformers(provider, transformer, body);\n\n if (bypass) {\n if (headers instanceof Headers) {\n headers.delete(\"content-length\");\n } else {\n delete headers[\"content-length\"];\n }\n config.headers = headers;\n }\n\n // \u6267\u884Ctransformer\u7684transformRequestOut\u65B9\u6CD5\n if (!bypass && typeof transformer.transformRequestOut === \"function\") {\n const transformOut = await transformer.transformRequestOut(requestBody);\n if (transformOut.body) {\n requestBody = transformOut.body;\n config = transformOut.config || {};\n } else {\n requestBody = transformOut;\n }\n }\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of provider.transformer.use) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n const transformIn = await providerTransformer.transformRequestIn(\n requestBody,\n provider\n );\n if (transformIn.body) {\n requestBody = transformIn.body;\n config = { ...config, ...transformIn.config };\n } else {\n requestBody = transformIn;\n }\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[body.model]?.use?.length) {\n for (const modelTransformer of provider.transformer[body.model].use) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n requestBody = await modelTransformer.transformRequestIn(\n requestBody,\n provider\n );\n }\n }\n\n return { requestBody, config, bypass };\n}\n\n/**\n * \u5224\u65AD\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n * \u5F53provider\u53EA\u4F7F\u7528\u4E00\u4E2Atransformer\u4E14\u8BE5transformer\u4E0E\u5F53\u524Dtransformer\u76F8\u540C\u65F6\uFF0C\u8DF3\u8FC7\u5176\u4ED6\u8F6C\u6362\u5668\n */\nfunction shouldBypassTransformers(\n provider: any,\n transformer: any,\n body: any\n): boolean {\n return (\n provider.transformer?.use?.length === 1 &&\n provider.transformer.use[0].name === transformer.name &&\n (!provider.transformer?.[body.model]?.use.length ||\n (provider.transformer?.[body.model]?.use.length === 1 &&\n provider.transformer?.[body.model]?.use[0].name === transformer.name))\n );\n}\n\n/**\n * \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n * \u5904\u7406\u8BA4\u8BC1\u3001\u6784\u5EFA\u8BF7\u6C42\u914D\u7F6E\u3001\u53D1\u9001\u8BF7\u6C42\u5E76\u5904\u7406\u9519\u8BEF\n */\nasync function sendRequestToProvider(\n requestBody: any,\n config: any,\n provider: any,\n fastify: FastifyInstance,\n bypass: boolean,\n transformer: any\n) {\n const url = config.url || new URL(provider.baseUrl);\n\n // \u5728\u900F\u4F20\u53C2\u6570\u4E0B\u5904\u7406\u8BA4\u8BC1\n if (bypass && typeof transformer.auth === \"function\") {\n const auth = await transformer.auth(requestBody, provider);\n if (auth.body) {\n requestBody = auth.body;\n let headers = config.headers || {};\n if (auth.config?.headers) {\n headers = {\n ...headers,\n ...auth.config.headers,\n };\n delete headers.host;\n delete auth.config.headers;\n }\n config = {\n ...config,\n ...auth.config,\n headers,\n };\n } else {\n requestBody = auth;\n }\n }\n\n // \u53D1\u9001HTTP\u8BF7\u6C42\n const response = await sendUnifiedRequest(\n url,\n requestBody,\n {\n httpsProxy: fastify._server!.configService.getHttpsProxy(),\n ...config,\n headers: {\n Authorization: `Bearer ${provider.apiKey}`,\n ...(config?.headers || {}),\n },\n },\n fastify.log\n );\n\n // \u5904\u7406\u8BF7\u6C42\u9519\u8BEF\n if (!response.ok) {\n const errorText = await response.text();\n throw createApiError(\n `Error from provider(${provider.name},${requestBody.model}: ${response.status}): ${errorText}`,\n response.status,\n \"provider_response_error\"\n );\n }\n\n return response;\n}\n\n/**\n * \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884Cprovider transformers\u3001model-specific transformers\u3001transformer\u7684transformResponseIn\n */\nasync function processResponseTransformers(\n requestBody: any,\n response: any,\n provider: any,\n transformer: any,\n bypass: boolean\n) {\n let finalResponse = response;\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of Array.from(\n provider.transformer.use\n ).reverse()) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await providerTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[requestBody.model]?.use?.length) {\n for (const modelTransformer of Array.from(\n provider.transformer[requestBody.model].use\n ).reverse()) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await modelTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884Ctransformer\u7684transformResponseIn\u65B9\u6CD5\n if (!bypass && transformer.transformResponseIn) {\n finalResponse = await transformer.transformResponseIn(finalResponse);\n }\n\n return finalResponse;\n}\n\n/**\n * \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n * \u5904\u7406HTTP\u72B6\u6001\u7801\u3001\u6D41\u5F0F\u54CD\u5E94\u548C\u666E\u901A\u54CD\u5E94\u7684\u683C\u5F0F\u5316\n */\nfunction formatResponse(response: any, reply: FastifyReply, body: any) {\n // \u8BBE\u7F6EHTTP\u72B6\u6001\u7801\n if (!response.ok) {\n reply.code(response.status);\n }\n\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n const isStream = body.stream === true;\n if (isStream) {\n reply.header(\"Content-Type\", \"text/event-stream\");\n reply.header(\"Cache-Control\", \"no-cache\");\n reply.header(\"Connection\", \"keep-alive\");\n return reply.send(response.body);\n } else {\n // \u5904\u7406\u666E\u901AJSON\u54CD\u5E94\n return response.json();\n }\n}\n\nexport const registerApiRoutes: FastifyPluginAsync = async (\n fastify: FastifyInstance\n) => {\n // Health and info endpoints\n fastify.get(\"/\", async () => {\n return { message: \"LLMs API\", version };\n });\n\n fastify.get(\"/health\", async () => {\n return { status: \"ok\", timestamp: new Date().toISOString() };\n });\n\n const transformersWithEndpoint =\n fastify._server!.transformerService.getTransformersWithEndpoint();\n\n for (const { transformer } of transformersWithEndpoint) {\n if (transformer.endPoint) {\n fastify.post(\n transformer.endPoint,\n async (req: FastifyRequest, reply: FastifyReply) => {\n return handleTransformerEndpoint(req, reply, fastify, transformer);\n }\n );\n }\n }\n\n fastify.post(\n \"/providers\",\n {\n schema: {\n body: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"id\", \"name\", \"type\", \"baseUrl\", \"apiKey\", \"models\"],\n },\n },\n },\n async (\n request: FastifyRequest<{ Body: RegisterProviderRequest }>,\n reply: FastifyReply\n ) => {\n // Validation\n const { name, baseUrl, apiKey, models } = request.body;\n\n if (!name?.trim()) {\n throw createApiError(\n \"Provider name is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!baseUrl || !isValidUrl(baseUrl)) {\n throw createApiError(\n \"Valid base URL is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!apiKey?.trim()) {\n throw createApiError(\"API key is required\", 400, \"invalid_request\");\n }\n\n if (!models || !Array.isArray(models) || models.length === 0) {\n throw createApiError(\n \"At least one model is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n // Check if provider already exists\n if (fastify._server!.providerService.getProvider(request.body.name)) {\n throw createApiError(\n `Provider with name '${request.body.name}' already exists`,\n 400,\n \"provider_exists\"\n );\n }\n\n return fastify._server!.providerService.registerProvider(request.body);\n }\n );\n\n fastify.get(\"/providers\", async () => {\n return fastify._server!.providerService.getProviders();\n });\n\n fastify.get(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const provider = fastify._server!.providerService.getProvider(\n request.params.id\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.put(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n enabled: { type: \"boolean\" },\n },\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: Partial;\n }>,\n reply\n ) => {\n const provider = fastify._server!.providerService.updateProvider(\n request.params.id,\n request.body\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.delete(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const success = fastify._server!.providerService.deleteProvider(\n request.params.id\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return { message: \"Provider deleted successfully\" };\n }\n );\n\n fastify.patch(\n \"/providers/:id/toggle\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: { enabled: { type: \"boolean\" } },\n required: [\"enabled\"],\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: { enabled: boolean };\n }>,\n reply\n ) => {\n const success = fastify._server!.providerService.toggleProvider(\n request.params.id,\n request.body.enabled\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return {\n message: `Provider ${\n request.body.enabled ? \"enabled\" : \"disabled\"\n } successfully`,\n };\n }\n );\n};\n\n// Helper function\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n", "import { ProviderService } from \"./provider\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n RequestRouteInfo,\n} from \"../types/llm\";\n\nexport class LLMService {\n constructor(private readonly providerService: ProviderService) {\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n return this.providerService.registerProvider(request);\n }\n\n getProviders(): LLMProvider[] {\n return this.providerService.getProviders();\n }\n\n getProvider(id: string): LLMProvider | undefined {\n return this.providerService.getProvider(id);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const result = this.providerService.updateProvider(id, updates);\n return result;\n }\n\n deleteProvider(id: string): boolean {\n const result = this.providerService.deleteProvider(id);\n return result;\n }\n\n toggleProvider(id: string, enabled: boolean): boolean {\n return this.providerService.toggleProvider(id, enabled);\n }\n\n private resolveRoute(modelName: string): RequestRouteInfo {\n const route = this.providerService.resolveModelRoute(modelName);\n if (!route) {\n throw new Error(\n `Model ${modelName} not found. Available models: ${this.getAvailableModelNames().join(\n \", \"\n )}`\n );\n }\n return route;\n }\n\n async getAvailableModels(): Promise {\n const providers = this.providerService.getAvailableModels();\n\n return {\n object: \"list\",\n data: providers.flatMap((provider) =>\n provider.models.map((model) => ({\n id: model,\n object: \"model\",\n provider: provider.provider,\n created: Math.floor(Date.now() / 1000),\n owned_by: provider.provider,\n }))\n ),\n };\n }\n\n private getAvailableModelNames(): string[] {\n return this.providerService\n .getModelRoutes()\n .map((route) => route.fullModel);\n }\n\n getModelRoutes() {\n return this.providerService.getModelRoutes();\n }\n}\n", "import { TransformerConstructor } from \"@/types/transformer\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n ModelRoute,\n RequestRouteInfo,\n ConfigProvider,\n} from \"../types/llm\";\nimport { ConfigService } from \"./config\";\nimport { TransformerService } from \"./transformer\";\n\nexport class ProviderService {\n private providers: Map = new Map();\n private modelRoutes: Map = new Map();\n\n constructor(private readonly configService: ConfigService, private readonly transformerService: TransformerService, private readonly logger: any) {\n this.initializeCustomProviders();\n }\n\n private initializeCustomProviders() {\n const providersConfig =\n this.configService.get(\"providers\");\n if (providersConfig && Array.isArray(providersConfig)) {\n this.initializeFromProvidersArray(providersConfig);\n return;\n }\n }\n\n private initializeFromProvidersArray(providersConfig: ConfigProvider[]) {\n providersConfig.forEach((providerConfig: ConfigProvider) => {\n try {\n if (\n !providerConfig.name ||\n !providerConfig.api_base_url ||\n !providerConfig.api_key\n ) {\n return;\n }\n\n const transformer: LLMProvider[\"transformer\"] = {}\n\n if (providerConfig.transformer) {\n Object.keys(providerConfig.transformer).forEach(key => {\n if (key === 'use') {\n if (Array.isArray(providerConfig.transformer.use)) {\n transformer.use = providerConfig.transformer.use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined');\n }\n } else {\n if (Array.isArray(providerConfig.transformer[key]?.use)) {\n transformer[key] = {\n use: providerConfig.transformer[key].use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined')\n }\n }\n }\n })\n }\n\n this.registerProvider({\n name: providerConfig.name,\n baseUrl: providerConfig.api_base_url,\n apiKey: providerConfig.api_key,\n models: providerConfig.models || [],\n transformer: providerConfig.transformer ? transformer : undefined,\n });\n\n this.logger.info(`${providerConfig.name} provider registered`);\n } catch (error) {\n this.logger.error(`${providerConfig.name} provider registered error: ${error}`);\n }\n });\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n const provider: LLMProvider = {\n ...request,\n };\n\n this.providers.set(provider.name, provider);\n\n request.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n\n return provider;\n }\n\n getProviders(): LLMProvider[] {\n return Array.from(this.providers.values());\n }\n\n getProvider(name: string): LLMProvider | undefined {\n return this.providers.get(name);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const provider = this.providers.get(id);\n if (!provider) {\n return null;\n }\n\n const updatedProvider = {\n ...provider,\n ...updates,\n updatedAt: new Date(),\n };\n\n this.providers.set(id, updatedProvider);\n\n if (updates.models) {\n provider.models.forEach((model) => {\n const fullModel = `${provider.id},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n updates.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n }\n\n return updatedProvider;\n }\n\n deleteProvider(id: string): boolean {\n const provider = this.providers.get(id);\n if (!provider) {\n return false;\n }\n\n provider.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n this.providers.delete(id);\n return true;\n }\n\n toggleProvider(name: string, enabled: boolean): boolean {\n const provider = this.providers.get(name);\n if (!provider) {\n return false;\n }\n return true;\n }\n\n resolveModelRoute(modelName: string): RequestRouteInfo | null {\n const route = this.modelRoutes.get(modelName);\n if (!route) {\n return null;\n }\n\n const provider = this.providers.get(route.provider);\n if (!provider) {\n return null;\n }\n\n return {\n provider,\n originalModel: modelName,\n targetModel: route.model,\n };\n }\n\n getAvailableModelNames(): string[] {\n const modelNames: string[] = [];\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n modelNames.push(model);\n modelNames.push(`${provider.name},${model}`);\n });\n });\n return modelNames;\n }\n\n getModelRoutes(): ModelRoute[] {\n return Array.from(this.modelRoutes.values());\n }\n\n private parseTransformerConfig(transformerConfig: any): any {\n if (!transformerConfig) return {};\n\n if (Array.isArray(transformerConfig)) {\n return transformerConfig.reduce((acc, item) => {\n if (Array.isArray(item)) {\n const [name, config = {}] = item;\n acc[name] = config;\n } else {\n acc[item] = {};\n }\n return acc;\n }, {});\n }\n\n return transformerConfig;\n }\n\n async getAvailableModels(): Promise<{\n object: string;\n data: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }>;\n }> {\n const models: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }> = [];\n\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n models.push({\n id: model,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n\n models.push({\n id: `${provider.name},${model}`,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n });\n });\n\n return {\n object: \"list\",\n data: models,\n };\n }\n}\n", "import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n", "import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n", "import { randomUUID } from 'crypto';\nexport default { randomUUID };\n", "import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n", "import { ThinkLevel } from \"@/types/llm\";\n\nexport const getThinkLevel = (thinking_budget: number): ThinkLevel => {\n if (thinking_budget <= 0) return \"none\";\n if (thinking_budget <= 1024) return \"low\";\n if (thinking_budget <= 8192) return \"medium\";\n return \"high\";\n};\n", "import { ChatCompletion } from \"openai/resources\";\nimport {\n LLMProvider,\n UnifiedChatRequest,\n UnifiedMessage,\n UnifiedTool,\n} from \"@/types/llm\";\nimport { Transformer, TransformerContext } from \"@/types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { getThinkLevel } from \"@/utils/thinking\";\nimport { createApiError } from \"@/api/middleware\";\n\nexport class AnthropicTransformer implements Transformer {\n name = \"Anthropic\";\n endPoint = \"/v1/messages\";\n\n async auth(request: any, provider: LLMProvider): Promise {\n return {\n body: request,\n config: {\n headers: {\n \"x-api-key\": provider.apiKey,\n authorization: undefined,\n },\n },\n };\n }\n\n async transformRequestOut(\n request: Record\n ): Promise {\n const messages: UnifiedMessage[] = [];\n\n if (request.system) {\n if (typeof request.system === \"string\") {\n messages.push({\n role: \"system\",\n content: request.system,\n });\n } else if (Array.isArray(request.system) && request.system.length) {\n const textParts = request.system\n .filter((item: any) => item.type === \"text\" && item.text)\n .map((item: any) => ({\n type: \"text\" as const,\n text: item.text,\n cache_control: item.cache_control,\n }));\n messages.push({\n role: \"system\",\n content: textParts,\n });\n }\n }\n\n const requestMessages = JSON.parse(JSON.stringify(request.messages || []));\n\n requestMessages?.forEach((msg: any, index: number) => {\n if (msg.role === \"user\" || msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: msg.role,\n content: msg.content,\n });\n return;\n }\n\n if (Array.isArray(msg.content)) {\n if (msg.role === \"user\") {\n const toolParts = msg.content.filter(\n (c: any) => c.type === \"tool_result\" && c.tool_use_id\n );\n if (toolParts.length) {\n toolParts.forEach((tool: any, toolIndex: number) => {\n const toolMessage: UnifiedMessage = {\n role: \"tool\",\n content:\n typeof tool.content === \"string\"\n ? tool.content\n : JSON.stringify(tool.content),\n tool_call_id: tool.tool_use_id,\n cache_control: tool.cache_control,\n };\n messages.push(toolMessage);\n });\n }\n\n const textAndMediaParts = msg.content.filter(\n (c: any) =>\n (c.type === \"text\" && c.text) ||\n (c.type === \"image\" && c.source)\n );\n if (textAndMediaParts.length) {\n messages.push({\n role: \"user\",\n content: textAndMediaParts.map((part: any) => {\n if (part?.type === \"image\") {\n return {\n type: \"image_url\",\n image_url: {\n url:\n part.source?.type === \"base64\"\n ? part.source.data\n : part.source.url,\n },\n media_type: part.source.media_type,\n };\n }\n return part;\n }),\n });\n }\n } else if (msg.role === \"assistant\") {\n const assistantMessage: UnifiedMessage = {\n role: \"assistant\",\n content: null,\n };\n const textParts = msg.content.filter(\n (c: any) => c.type === \"text\" && c.text\n );\n if (textParts.length) {\n assistantMessage.content = textParts\n .map((text: any) => text.text)\n .join(\"\\n\");\n }\n\n const toolCallParts = msg.content.filter(\n (c: any) => c.type === \"tool_use\" && c.id\n );\n if (toolCallParts.length) {\n assistantMessage.tool_calls = toolCallParts.map((tool: any) => {\n return {\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input || {}),\n },\n };\n });\n }\n messages.push(assistantMessage);\n }\n return;\n }\n }\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model,\n max_tokens: request.max_tokens,\n temperature: request.temperature,\n stream: request.stream,\n tools: request.tools?.length\n ? this.convertAnthropicToolsToUnified(request.tools)\n : undefined,\n tool_choice: request.tool_choice,\n };\n if (request.thinking) {\n result.reasoning = {\n effort: getThinkLevel(request.thinking.budget_tokens),\n // max_tokens: request.thinking.budget_tokens,\n enabled: request.thinking.type === \"enabled\",\n };\n }\n if (request.tool_choice) {\n if (request.tool_choice.type === \"tool\") {\n result.tool_choice = {\n type: \"function\",\n function: { name: request.tool_choice.name },\n };\n } else {\n result.tool_choice = request.tool_choice.type;\n }\n }\n return result;\n }\n\n async transformResponseIn(\n response: Response,\n context?: TransformerContext\n ): Promise {\n const isStream = response.headers\n .get(\"Content-Type\")\n ?.includes(\"text/event-stream\");\n if (isStream) {\n if (!response.body) {\n throw new Error(\"Stream response body is null\");\n }\n const convertedStream = await this.convertOpenAIStreamToAnthropic(\n response.body\n );\n return new Response(convertedStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n } else {\n const data = await response.json();\n const anthropicResponse = this.convertOpenAIResponseToAnthropic(data);\n return new Response(JSON.stringify(anthropicResponse), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n }\n\n private convertAnthropicToolsToUnified(tools: any[]): UnifiedTool[] {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description || \"\",\n parameters: tool.input_schema,\n },\n }));\n }\n\n private async convertOpenAIStreamToAnthropic(\n openaiStream: ReadableStream\n ): Promise {\n const readable = new ReadableStream({\n start: async (controller) => {\n const encoder = new TextEncoder();\n const messageId = `msg_${Date.now()}`;\n let stopReasonMessageDelta: null | Record = null;\n let model = \"unknown\";\n let hasStarted = false;\n let hasTextContentStarted = false;\n let hasFinished = false;\n const toolCalls = new Map();\n const toolCallIndexToContentBlockIndex = new Map();\n let totalChunks = 0;\n let contentChunks = 0;\n let toolCallChunks = 0;\n let isClosed = false;\n let isThinkingStarted = false;\n let contentIndex = 0;\n let currentContentBlockIndex = -1; // Track the current content block index\n\n const safeEnqueue = (data: Uint8Array) => {\n if (!isClosed) {\n try {\n controller.enqueue(data);\n const dataStr = new TextDecoder().decode(data);\n this.logger.debug({ dataStr }, `send data`);\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n this.logger.debug(`send data error: ${error.message}`);\n throw error;\n }\n }\n }\n };\n\n const safeClose = () => {\n if (!isClosed) {\n try {\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (stopReasonMessageDelta) {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify(\n stopReasonMessageDelta\n )}\\n\\n`\n )\n );\n stopReasonMessageDelta = null;\n } else {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify({\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_read_input_tokens: 0,\n },\n })}\\n\\n`\n )\n );\n }\n const messageStop = {\n type: \"message_stop\",\n };\n safeEnqueue(\n encoder.encode(\n `event: message_stop\\ndata: ${JSON.stringify(\n messageStop\n )}\\n\\n`\n )\n );\n controller.close();\n isClosed = true;\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n throw error;\n }\n }\n }\n };\n\n let reader: ReadableStreamDefaultReader | null = null;\n\n try {\n reader = openaiStream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n if (isClosed) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (isClosed || hasFinished) break;\n\n if (!line.startsWith(\"data:\")) continue;\n const data = line.slice(5).trim();\n this.logger.debug(`recieved data: ${data}`);\n\n if (data === \"[DONE]\") {\n continue;\n }\n\n try {\n const chunk = JSON.parse(data);\n totalChunks++;\n this.logger.debug({ response: chunk }, `Original Response`);\n if (chunk.error) {\n const errorMessage = {\n type: \"error\",\n message: {\n type: \"api_error\",\n message: JSON.stringify(chunk.error),\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: error\\ndata: ${JSON.stringify(errorMessage)}\\n\\n`\n )\n );\n continue;\n }\n\n model = chunk.model || model;\n\n if (!hasStarted && !isClosed && !hasFinished) {\n hasStarted = true;\n\n const messageStart = {\n type: \"message_start\",\n message: {\n id: messageId,\n type: \"message\",\n role: \"assistant\",\n content: [],\n model: model,\n stop_reason: null,\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n },\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: message_start\\ndata: ${JSON.stringify(\n messageStart\n )}\\n\\n`\n )\n );\n }\n\n const choice = chunk.choices?.[0];\n if (chunk.usage) {\n if (!stopReasonMessageDelta) {\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n } else {\n stopReasonMessageDelta.usage = {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n };\n }\n }\n if (!choice) {\n continue;\n }\n\n if (choice?.delta?.thinking && !isClosed && !hasFinished) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isThinkingStarted) {\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: { type: \"thinking\", thinking: \"\" },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n isThinkingStarted = true;\n }\n if (choice.delta.thinking.signature) {\n const thinkingSignature = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"signature_delta\",\n signature: choice.delta.thinking.signature,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingSignature\n )}\\n\\n`\n )\n );\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n contentIndex++;\n } else if (choice.delta.thinking.content) {\n const thinkingChunk = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"thinking_delta\",\n thinking: choice.delta.thinking.content || \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (choice?.delta?.content && !isClosed && !hasFinished) {\n contentChunks++;\n\n // Close any previous content block if open and it's not a text content block\n if (currentContentBlockIndex >= 0) {\n // Check if current content block is text type\n const isCurrentTextBlock = hasTextContentStarted;\n if (!isCurrentTextBlock) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n }\n\n if (!hasTextContentStarted && !hasFinished) {\n hasTextContentStarted = true;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"text\",\n text: \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n }\n\n if (!isClosed && !hasFinished) {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: currentContentBlockIndex, // Use current content block index\n delta: {\n type: \"text_delta\",\n text: choice.delta.content,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (\n choice?.delta?.annotations?.length &&\n !isClosed &&\n !hasFinished\n ) {\n // Close text content block if open\n if (currentContentBlockIndex >= 0 && hasTextContentStarted) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n hasTextContentStarted = false;\n }\n\n choice?.delta?.annotations.forEach((annotation: any) => {\n contentIndex++;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"web_search_tool_result\",\n tool_use_id: `srvtoolu_${uuidv4()}`,\n content: [\n {\n type: \"web_search_result\",\n title: annotation.url_citation.title,\n url: annotation.url_citation.url,\n },\n ],\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n });\n }\n\n if (choice?.delta?.tool_calls && !isClosed && !hasFinished) {\n toolCallChunks++;\n const processedInThisChunk = new Set();\n\n for (const toolCall of choice.delta.tool_calls) {\n if (isClosed) break;\n const toolCallIndex = toolCall.index ?? 0;\n if (processedInThisChunk.has(toolCallIndex)) {\n continue;\n }\n processedInThisChunk.add(toolCallIndex);\n const isUnknownIndex =\n !toolCallIndexToContentBlockIndex.has(toolCallIndex);\n\n if (isUnknownIndex) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n const newContentBlockIndex = contentIndex;\n toolCallIndexToContentBlockIndex.set(\n toolCallIndex,\n newContentBlockIndex\n );\n contentIndex++; // Increment contentIndex after setting the mapping\n const toolCallId =\n toolCall.id || `call_${Date.now()}_${toolCallIndex}`;\n const toolCallName =\n toolCall.function?.name || `tool_${toolCallIndex}`;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: newContentBlockIndex,\n content_block: {\n type: \"tool_use\",\n id: toolCallId,\n name: toolCallName,\n input: {},\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = newContentBlockIndex;\n\n const toolCallInfo = {\n id: toolCallId,\n name: toolCallName,\n arguments: \"\",\n contentBlockIndex: newContentBlockIndex,\n };\n toolCalls.set(toolCallIndex, toolCallInfo);\n } else if (toolCall.id && toolCall.function?.name) {\n const existingToolCall = toolCalls.get(toolCallIndex)!;\n const wasTemporary =\n existingToolCall.id.startsWith(\"call_\") &&\n existingToolCall.name.startsWith(\"tool_\");\n\n if (wasTemporary) {\n existingToolCall.id = toolCall.id;\n existingToolCall.name = toolCall.function.name;\n }\n }\n\n if (\n toolCall.function?.arguments &&\n !isClosed &&\n !hasFinished\n ) {\n const blockIndex =\n toolCallIndexToContentBlockIndex.get(toolCallIndex);\n if (blockIndex === undefined) {\n continue;\n }\n const currentToolCall = toolCalls.get(toolCallIndex);\n if (currentToolCall) {\n currentToolCall.arguments +=\n toolCall.function.arguments;\n }\n\n try {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: toolCall.function.arguments,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n } catch (error) {\n try {\n const fixedArgument = toolCall.function.arguments\n .replace(/[\\x00-\\x1F\\x7F-\\x9F]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n\n const fixedChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: fixedArgument,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n fixedChunk\n )}\\n\\n`\n )\n );\n } catch (fixError) {\n console.error(fixError);\n }\n }\n }\n }\n }\n\n if (choice?.finish_reason && !isClosed && !hasFinished) {\n if (contentChunks === 0 && toolCallChunks === 0) {\n console.error(\n \"Warning: No content in the stream response!\"\n );\n }\n\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isClosed) {\n const stopReasonMapping: Record = {\n stop: \"end_turn\",\n length: \"max_tokens\",\n tool_calls: \"tool_use\",\n content_filter: \"stop_sequence\",\n };\n\n const anthropicStopReason =\n stopReasonMapping[choice.finish_reason] || \"end_turn\";\n\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: anthropicStopReason,\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n }\n\n break;\n }\n } catch (parseError: any) {\n this.logger?.error(\n `parseError: ${parseError.name} message: ${parseError.message} stack: ${parseError.stack} data: ${data}`\n );\n }\n }\n }\n safeClose();\n } catch (error) {\n if (!isClosed) {\n try {\n controller.error(error);\n } catch (controllerError) {\n console.error(controllerError);\n }\n }\n } finally {\n if (reader) {\n try {\n reader.releaseLock();\n } catch (releaseError) {\n console.error(releaseError);\n }\n }\n }\n },\n cancel: (reason) => {\n this.logger.debug(`cancle stream: ${reason}`);\n },\n });\n\n return readable;\n }\n\n private convertOpenAIResponseToAnthropic(\n openaiResponse: ChatCompletion\n ): any {\n this.logger.debug({ response: openaiResponse }, `Original OpenAI response`);\n try {\n const choice = openaiResponse.choices[0];\n if (!choice) {\n throw new Error(\"No choices found in OpenAI response\");\n }\n const content: any[] = [];\n if (choice.message.annotations) {\n const id = `srvtoolu_${uuidv4()}`;\n content.push({\n type: \"server_tool_use\",\n id,\n name: \"web_search\",\n input: {\n query: \"\",\n },\n });\n content.push({\n type: \"web_search_tool_result\",\n tool_use_id: id,\n content: choice.message.annotations.map((item) => {\n return {\n type: \"web_search_result\",\n url: item.url_citation.url,\n title: item.url_citation.title,\n };\n }),\n });\n }\n if (choice.message.content) {\n content.push({\n type: \"text\",\n text: choice.message.content,\n });\n }\n if (choice.message.tool_calls && choice.message.tool_calls.length > 0) {\n choice.message.tool_calls.forEach((toolCall, index) => {\n let parsedInput = {};\n try {\n const argumentsStr = toolCall.function.arguments || \"{}\";\n\n if (typeof argumentsStr === \"object\") {\n parsedInput = argumentsStr;\n } else if (typeof argumentsStr === \"string\") {\n parsedInput = JSON.parse(argumentsStr);\n }\n } catch (parseError) {\n parsedInput = { text: toolCall.function.arguments || \"\" };\n }\n\n content.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n });\n });\n }\n\n const result = {\n id: openaiResponse.id,\n type: \"message\",\n role: \"assistant\",\n model: openaiResponse.model,\n content: content,\n stop_reason:\n choice.finish_reason === \"stop\"\n ? \"end_turn\"\n : choice.finish_reason === \"length\"\n ? \"max_tokens\"\n : choice.finish_reason === \"tool_calls\"\n ? \"tool_use\"\n : choice.finish_reason === \"content_filter\"\n ? \"stop_sequence\"\n : \"end_turn\",\n stop_sequence: null,\n usage: {\n input_tokens: openaiResponse.usage?.prompt_tokens || 0,\n output_tokens: openaiResponse.usage?.completion_tokens || 0,\n },\n };\n this.logger.debug(\n { result },\n `Conversion complete, final Anthropic response`\n );\n return result;\n } catch (e) {\n throw createApiError(\n `Provider error: ${JSON.stringify(openaiResponse)}`,\n 500,\n \"provider_error\"\n );\n }\n }\n}\n", "import { UnifiedChatRequest, UnifiedMessage } from \"../types/llm\";\nimport { Content, ContentListUnion, Part, ToolListUnion } from \"@google/genai\";\n\nexport function cleanupParameters(obj: any, keyName?: string): void {\n if (!obj || typeof obj !== \"object\") {\n return;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) => {\n cleanupParameters(item);\n });\n return;\n }\n\n const validFields = new Set([\n \"type\",\n \"format\",\n \"title\",\n \"description\",\n \"nullable\",\n \"enum\",\n \"maxItems\",\n \"minItems\",\n \"properties\",\n \"required\",\n \"minProperties\",\n \"maxProperties\",\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"example\",\n \"anyOf\",\n \"propertyOrdering\",\n \"default\",\n \"items\",\n \"minimum\",\n \"maximum\",\n ]);\n\n if (keyName !== \"properties\") {\n Object.keys(obj).forEach((key) => {\n if (!validFields.has(key)) {\n delete obj[key];\n }\n });\n }\n\n if (obj.enum && obj.type !== \"string\") {\n delete obj.enum;\n }\n\n if (\n obj.type === \"string\" &&\n obj.format &&\n ![\"enum\", \"date-time\"].includes(obj.format)\n ) {\n delete obj.format;\n }\n\n Object.keys(obj).forEach((key) => {\n cleanupParameters(obj[key], key);\n });\n}\n\n// Type enum equivalent in JavaScript\nconst Type = {\n TYPE_UNSPECIFIED: \"TYPE_UNSPECIFIED\",\n STRING: \"STRING\",\n NUMBER: \"NUMBER\",\n INTEGER: \"INTEGER\",\n BOOLEAN: \"BOOLEAN\",\n ARRAY: \"ARRAY\",\n OBJECT: \"OBJECT\",\n NULL: \"NULL\",\n};\n\n/**\n * Transform the type field from an array of types to an array of anyOf fields.\n * @param {string[]} typeList - List of types\n * @param {Object} resultingSchema - The schema object to modify\n */\nfunction flattenTypeArrayToAnyOf(typeList: Array, resultingSchema: any): void {\n if (typeList.includes(\"null\")) {\n resultingSchema[\"nullable\"] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== \"null\");\n\n if (listWithoutNull.length === 1) {\n const upperCaseType = listWithoutNull[0].toUpperCase();\n resultingSchema[\"type\"] = Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema[\"anyOf\"] = [];\n for (const i of listWithoutNull) {\n const upperCaseType = i.toUpperCase();\n resultingSchema[\"anyOf\"].push({\n type: Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\n/**\n * Process a JSON schema to make it compatible with the GenAI API\n * @param {Object} _jsonSchema - The JSON schema to process\n * @returns {Object} - The processed schema\n */\nfunction processJsonSchema(_jsonSchema: any): any {\n const genAISchema = {};\n const schemaFieldNames = [\"items\"];\n const listSchemaFieldNames = [\"anyOf\"];\n const dictSchemaFieldNames = [\"properties\"];\n\n if (_jsonSchema[\"type\"] && _jsonSchema[\"anyOf\"]) {\n throw new Error(\"type and anyOf cannot be both populated.\");\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n */\n const incomingAnyOf = _jsonSchema[\"anyOf\"];\n if (\n incomingAnyOf != null &&\n Array.isArray(incomingAnyOf) &&\n incomingAnyOf.length == 2\n ) {\n if (incomingAnyOf[0] && incomingAnyOf[0][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[1];\n } else if (incomingAnyOf[1] && incomingAnyOf[1][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[0];\n }\n }\n\n if (_jsonSchema[\"type\"] && Array.isArray(_jsonSchema[\"type\"])) {\n flattenTypeArrayToAnyOf(_jsonSchema[\"type\"], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldValue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == \"type\") {\n if (fieldValue === \"null\") {\n throw new Error(\n \"type: null can not be the only possible type for the field.\"\n );\n }\n if (Array.isArray(fieldValue)) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n const upperCaseValue = fieldValue.toUpperCase();\n genAISchema[\"type\"] = Object.values(Type).includes(upperCaseValue)\n ? upperCaseValue\n : Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n genAISchema[fieldName] = processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue = [];\n for (const item of fieldValue) {\n if (item[\"type\"] == \"null\") {\n genAISchema[\"nullable\"] = true;\n continue;\n }\n listSchemaFieldValue.push(processJsonSchema(item));\n }\n genAISchema[fieldName] = listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue = {};\n for (const [key, value] of Object.entries(fieldValue)) {\n dictSchemaFieldValue[key] = processJsonSchema(value);\n }\n genAISchema[fieldName] = dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === \"additionalProperties\") {\n continue;\n }\n genAISchema[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n/**\n * Transform a tool object\n * @param {Object} tool - The tool object to transform\n * @returns {Object} - The transformed tool object\n */\nexport function tTool(tool: any): any {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes(\"$schema\")) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes(\"$schema\")) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): Record {\n const tools = [];\n const functionDeclarations = request.tools\n ?.filter((tool) => tool.function.name !== \"web_search\")\n ?.map((tool) => {\n return {\n name: tool.function.name,\n description: tool.function.description,\n parametersJsonSchema: tool.function.parameters,\n };\n });\n if (functionDeclarations?.length) {\n tools.push(\n tTool({\n functionDeclarations,\n })\n );\n }\n const webSearch = request.tools?.find(\n (tool) => tool.function.name === \"web_search\"\n );\n if (webSearch) {\n tools.push({\n googleSearch: {},\n });\n }\n\n const contents = request.messages.map((message: UnifiedMessage) => {\n let role: \"user\" | \"model\";\n if (message.role === \"assistant\") {\n role = \"model\";\n } else if ([\"user\", \"system\", \"tool\"].includes(message.role)) {\n role = \"user\";\n } else {\n role = \"user\"; // Default to user if role is not recognized\n }\n const parts = [];\n if (typeof message.content === \"string\") {\n parts.push({\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n parts.push(\n ...message.content.map((content) => {\n if (content.type === \"text\") {\n return {\n text: content.text || \"\",\n };\n }\n if (content.type === \"image_url\") {\n if (content.image_url.url.startsWith(\"http\")) {\n return {\n file_data: {\n mime_type: content.media_type,\n file_uri: content.image_url.url,\n },\n };\n } else {\n return {\n inlineData: {\n mime_type: content.media_type,\n data: content.image_url.url,\n },\n };\n }\n }\n })\n );\n }\n\n if (Array.isArray(message.tool_calls)) {\n parts.push(\n ...message.tool_calls.map((toolCall) => {\n return {\n functionCall: {\n id:\n toolCall.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments || \"{}\"),\n },\n };\n })\n );\n }\n return {\n role,\n parts,\n };\n });\n\n const body = {\n contents,\n tools: tools.length ? tools : undefined,\n };\n\n if (request.tool_choice) {\n const toolConfig = {\n functionCallingConfig: {},\n };\n if (request.tool_choice === \"auto\") {\n toolConfig.functionCallingConfig.mode = \"auto\";\n } else if (request.tool_choice === \"none\") {\n toolConfig.functionCallingConfig.mode = \"none\";\n } else if (request.tool_choice === \"required\") {\n toolConfig.functionCallingConfig.mode = \"any\";\n } else if (request.tool_choice?.function?.name) {\n toolConfig.functionCallingConfig.mode = \"any\";\n toolConfig.functionCallingConfig.allowedFunctionNames = [\n request.tool_choice?.function?.name,\n ];\n }\n body.toolConfig = toolConfig;\n }\n\n return body;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const contents: ContentListUnion = request.contents;\n const tools: ToolListUnion = request.tools;\n const model: string = request.model;\n const max_tokens: number | undefined = request.max_tokens;\n const temperature: number | undefined = request.temperature;\n const stream: boolean | undefined = request.stream;\n const tool_choice: \"auto\" | \"none\" | string | undefined = request.tool_choice;\n\n const unifiedChatRequest: UnifiedChatRequest = {\n messages: [],\n model,\n max_tokens,\n temperature,\n stream,\n tool_choice,\n };\n\n if (Array.isArray(contents)) {\n contents.forEach((content) => {\n if (typeof content === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content,\n });\n } else if (typeof (content as Part).text === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content: (content as Part).text || null,\n });\n } else if ((content as Content).role === \"user\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n } else if ((content as Content).role === \"model\") {\n unifiedChatRequest.messages.push({\n role: \"assistant\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n }\n });\n }\n\n if (Array.isArray(tools)) {\n unifiedChatRequest.tools = [];\n tools.forEach((tool) => {\n if (Array.isArray(tool.functionDeclarations)) {\n tool.functionDeclarations.forEach((tool) => {\n unifiedChatRequest.tools!.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n });\n });\n }\n });\n }\n\n return unifiedChatRequest;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse: any = await response.json();\n const tool_calls =\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.functionCall)\n ?.map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n })) || [];\n const res = {\n id: jsonResponse.responseId,\n choices: [\n {\n finish_reason:\n (\n jsonResponse.candidates[0].finishReason as string\n )?.toLowerCase() || null,\n index: 0,\n message: {\n content:\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.text)\n ?.map((part: Part) => part.text)\n ?.join(\"\\n\") || \"\",\n role: \"assistant\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.modelVersion,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usageMetadata.candidatesTokenCount,\n prompt_tokens: jsonResponse.usageMetadata.promptTokenCount,\n cached_content_token_count:\n jsonResponse.usageMetadata.cachedContentTokenCount || null,\n total_tokens: jsonResponse.usageMetadata.totalTokenCount,\n },\n };\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // Check if chunk has valid structure\n if (!chunk.candidates || !chunk.candidates[0]) {\n log(`Invalid chunk structure:`, chunkStr);\n return;\n }\n\n const candidate = chunk.candidates[0];\n const parts = candidate.content?.parts || [];\n\n const tool_calls = parts\n .filter((part: Part) => part.functionCall)\n .map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n }));\n\n const textContent = parts\n .filter((part: Part) => part.text)\n .map((part: Part) => part.text)\n .join(\"\\n\");\n\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: textContent || \"\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n finish_reason: candidate.finishReason?.toLowerCase() || null,\n index: candidate.index || (tool_calls.length > 0 ? 1 : 0),\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.responseId || \"\",\n model: chunk.modelVersion || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens:\n chunk.usageMetadata?.candidatesTokenCount || 0,\n prompt_tokens: chunk.usageMetadata?.promptTokenCount || 0,\n cached_content_token_count:\n chunk.usageMetadata?.cachedContentTokenCount || null,\n total_tokens: chunk.usageMetadata?.totalTokenCount || 0,\n },\n };\n if (candidate?.groundingMetadata?.groundingChunks?.length) {\n res.choices[0].delta.annotations =\n candidate.groundingMetadata.groundingChunks.map(\n (groundingChunk, index) => {\n const support =\n candidate?.groundingMetadata?.groundingSupports?.filter(\n (item) => item.groundingChunkIndices?.includes(index)\n );\n return {\n type: \"url_citation\",\n url_citation: {\n url: groundingChunk?.web?.uri || \"\",\n title: groundingChunk?.web?.title || \"\",\n content: support?.[0]?.segment?.text || \"\",\n start_index: support?.[0]?.segment?.startIndex || 0,\n end_index: support?.[0]?.segment?.endIndex || 0,\n },\n };\n }\n );\n }\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nexport class GeminiTransformer implements Transformer {\n name = \"gemini\";\n\n endPoint = \"/v1beta/models/:modelAndAction\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./${request.model}:${\n request.stream ? \"streamGenerateContent?alt=sse\" : \"generateContent\"\n }`,\n provider.baseUrl\n ),\n headers: {\n \"x-goog-api-key\": provider.apiKey,\n Authorization: undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\nexport class VertexGeminiTransformer implements Transformer {\n name = \"vertex-gemini\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./v1beta1/projects/${projectId}/locations/${location}/publishers/google/models/${request.model}:${request.stream ? \"streamGenerateContent\" : \"generateContent\"}`,\n provider.baseUrl.endsWith('/') ? provider.baseUrl : provider.baseUrl + '/' || `https://${location}-aiplatform.googleapis.com`\n ),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"x-goog-api-key\": undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name);\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class DeepseekTransformer implements Transformer {\n name = \"deepseek\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > 8192) {\n request.max_tokens = 8192; // DeepSeek has a max token limit of 8192\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: typeof TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") || \"text/plain\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class TooluseTransformer implements Transformer {\n name = \"tooluse\";\n\n transformRequestIn(request: UnifiedChatRequest): UnifiedChatRequest {\n request.messages.push({\n role: \"system\",\n content: `Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the \\`ExitTool\\` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.`,\n });\n if (request.tools?.length) {\n request.tool_choice = \"required\";\n request.tools.push({\n type: \"function\",\n function: {\n name: \"ExitTool\",\n description: `Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.\nIMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.\nExamples:\n1. Task: \"Use a tool to summarize this document\" \u2014 Do not use ExitTool if a summarization tool is available.\n2. Task: \"What\u2019s the weather today?\" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,\n parameters: {\n type: \"object\",\n properties: {\n response: {\n type: \"string\",\n description:\n \"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way.\",\n },\n },\n required: [\"response\"],\n },\n },\n });\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (\n jsonResponse?.choices?.[0]?.message.tool_calls?.length &&\n jsonResponse?.choices?.[0]?.message.tool_calls[0]?.function?.name ===\n \"ExitTool\"\n ) {\n const toolCall = jsonResponse?.choices[0]?.message.tool_calls[0];\n const toolArguments = JSON.parse(toolCall.function.arguments || \"{}\");\n jsonResponse.choices[0].message.content = toolArguments.response || \"\";\n delete jsonResponse.choices[0].message.tool_calls;\n }\n\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let exitToolIndex = -1;\n let exitToolResponse = \"\";\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n exitToolIndex: () => number;\n setExitToolIndex: (val: number) => void;\n exitToolResponse: () => string;\n appendExitToolResponse: (content: string) => void;\n }\n ) => {\n const {\n controller,\n encoder,\n exitToolIndex,\n setExitToolIndex,\n appendExitToolResponse,\n } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n if (data.choices[0]?.delta?.tool_calls?.length) {\n const toolCall = data.choices[0].delta.tool_calls[0];\n\n if (toolCall.function?.name === \"ExitTool\") {\n setExitToolIndex(toolCall.index);\n return;\n } else if (\n exitToolIndex() > -1 &&\n toolCall.index === exitToolIndex() &&\n toolCall.function.arguments\n ) {\n appendExitToolResponse(toolCall.function.arguments);\n try {\n const response = JSON.parse(context.exitToolResponse());\n data.choices = [\n {\n delta: {\n role: \"assistant\",\n content: response.response || \"\",\n },\n },\n ];\n const modifiedLine = `data: ${JSON.stringify(\n data\n )}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {}\n return;\n }\n }\n\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n processLine(line, {\n controller,\n encoder,\n exitToolIndex: () => exitToolIndex,\n setExitToolIndex: (val) => (exitToolIndex = val),\n exitToolResponse: () => exitToolResponse,\n appendExitToolResponse: (content) =>\n (exitToolResponse += content),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class OpenrouterTransformer implements Transformer {\n static TransformerName = \"openrouter\";\n\n constructor(private readonly options?: TransformerOptions) {}\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.model.includes(\"claude\")) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.cache_control) {\n delete item.cache_control;\n }\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n } else {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n }\n });\n }\n Object.assign(request, this.options || {});\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.usage) {\n this.logger?.debug(\n { usage: data.usage, hasToolCall },\n \"usage\"\n );\n data.choices[0].finish_reason = hasToolCall\n ? \"tool_calls\"\n : \"stop\";\n }\n\n if (data.choices?.[0]?.finish_reason === \"error\") {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n error: data.choices?.[0].error,\n })}\\n\\n`\n )\n );\n }\n\n if (\n data.choices?.[0]?.delta?.content &&\n !context.hasTextContent()\n ) {\n context.setHasTextContent(true);\n }\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning) {\n delete data.choices[0].delta.reasoning;\n }\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !Number.isNaN(\n parseInt(data.choices?.[0]?.delta?.tool_calls[0].id, 10)\n )\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n });\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !hasToolCall\n ) {\n hasToolCall = true;\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class MaxTokenTransformer implements Transformer {\n static TransformerName = \"maxtoken\";\n max_tokens: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n }\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n return request;\n }\n}\n", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\"\n\nexport class GroqTransformer implements Transformer {\n name = \"groq\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n request.messages.forEach(msg => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n })\n if (Array.isArray(request.tools)) {\n request.tools.forEach(tool => {\n delete tool.function.parameters.$schema;\n })\n }\n return request\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (buffer: string, controller: ReadableStreamDefaultController, encoder: InstanceType) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (line: string, context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.error) {\n throw new Error(JSON.stringify(data));\n }\n\n if (data.choices?.[0]?.delta?.content && !context.hasTextContent()) {\n context.setHasTextContent(true);\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n })\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === 'number') {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) { // 1MB \u9650\u5236\n console.warn(\"Buffer size exceeds limit, processing partial data\");\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class CleancacheTransformer implements Transformer {\n name = \"cleancache\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (Array.isArray(request.messages)) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n }\n return request;\n }\n}\n", "import JSON5 from \"json5\";\nimport { jsonrepair } from \"jsonrepair\";\n\n/**\n * \u89E3\u6790\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u7684\u51FD\u6570\n * Parse tool call arguments function\n * \u5148\u5C1D\u8BD5\u6807\u51C6JSON\u89E3\u6790\uFF0C\u7136\u540EJSON5\u89E3\u6790\uFF0C\u6700\u540E\u4F7F\u7528jsonrepair\u8FDB\u884C\u5B89\u5168\u4FEE\u590D\n * First try standard JSON parsing, then JSON5 parsing, finally use jsonrepair for safe repair\n * \n * @param argsString - \u9700\u8981\u89E3\u6790\u7684\u53C2\u6570\u5B57\u7B26\u4E32 / Parameter string to parse\n * @returns \u89E3\u6790\u540E\u7684\u53C2\u6570\u5BF9\u8C61\u6216\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61 / Parsed parameter object or safe empty object\n */\nexport function parseToolArguments(argsString: string, logger?: any): string {\n // Handle empty or null input\n if (!argsString || argsString.trim() === \"\" || argsString === \"{}\") {\n return \"{}\";\n }\n\n try {\n // First attempt: Standard JSON parsing\n JSON.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful`);\n return argsString;\n } catch (jsonError: any) {\n try {\n // Second attempt: JSON5 parsing for relaxed syntax\n const args = JSON5.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful`);\n return JSON.stringify(args);\n } catch (json5Error: any) {\n try {\n // Third attempt: Safe JSON repair without code execution\n const repairedJson = jsonrepair(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired`);\n return repairedJson;\n } catch (repairError: any) {\n // All parsing attempts failed - log errors and return safe fallback\n logger?.error(\n `JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${jsonError.message}. ` +\n `JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${json5Error.message}. ` +\n `JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${repairError.message}. ` +\n `\u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(argsString)}`\n );\n \n // Return safe empty object as fallback instead of potentially malformed input\n logger?.debug(`\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback`);\n return \"{}\";\n }\n }\n }\n}", "export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n", "const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n", "import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += `\"${text.substring(start, i)}\"`\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n", "import { Transformer } from \"@/types/transformer\";\nimport { parseToolArguments } from \"@/utils/toolArgumentsParser\";\n\nexport class EnhanceToolTransformer implements Transformer {\n name = \"enhancetool\";\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (jsonResponse?.choices?.[0]?.message?.tool_calls?.length) {\n // \u5904\u7406\u975E\u6D41\u5F0F\u7684\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\n for (const toolCall of jsonResponse.choices[0].message.tool_calls) {\n if (toolCall.function?.arguments) {\n toolCall.function.arguments = parseToolArguments(\n toolCall.function.arguments,\n this.logger\n );\n }\n }\n }\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n // Define interface for tool call tracking\n interface ToolCall {\n index?: number;\n name?: string;\n id?: string;\n arguments?: string;\n }\n\n let currentToolCall: ToolCall = {};\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Helper function to process completed tool calls\n const processCompletedToolCall = (\n data: any,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n let finalArgs = \"\";\n try {\n finalArgs = parseToolArguments(currentToolCall.arguments || \"\", this.logger);\n } catch (e: any) {\n console.error(\n `${e.message} ${\n e.stack\n } \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(\n currentToolCall\n )}`\n );\n // Use original arguments if parsing fails\n finalArgs = currentToolCall.arguments || \"\";\n }\n\n const delta = {\n role: \"assistant\",\n tool_calls: [\n {\n function: {\n name: currentToolCall.name,\n arguments: finalArgs,\n },\n id: currentToolCall.id,\n index: currentToolCall.index,\n type: \"function\",\n },\n ],\n };\n\n // Remove content field entirely to prevent extra null values\n const modifiedData = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta,\n },\n ],\n };\n // Remove content field if it exists\n if (modifiedData.choices[0].delta.content !== undefined) {\n delete modifiedData.choices[0].delta.content;\n }\n\n const modifiedLine = `data: ${JSON.stringify(modifiedData)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n\n // Handle tool calls in streaming mode\n if (data.choices?.[0]?.delta?.tool_calls?.length) {\n const toolCallDelta = data.choices[0].delta.tool_calls[0];\n\n // Initialize currentToolCall if this is the first chunk for this tool call\n if (typeof currentToolCall.index === \"undefined\") {\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n if (toolCallDelta.function?.arguments) {\n toolCallDelta.function.arguments = ''\n }\n // Send the first chunk as-is\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n return;\n }\n // Accumulate arguments if this is a continuation of the current tool call\n else if (currentToolCall.index === toolCallDelta.index) {\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n // Don't send intermediate chunks that only contain arguments\n return;\n }\n // If we have a different tool call index, process the previous one and start a new one\n else {\n // Process the completed tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n\n // Start tracking the new tool call\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n return;\n }\n }\n\n // Handle finish_reason for tool_calls\n if (data.choices?.[0]?.finish_reason === \"tool_calls\" && currentToolCall.index !== undefined) {\n // Process the final tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n currentToolCall = {};\n return;\n }\n\n // Handle text content alongside tool calls\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class ReasoningTransformer implements Transformer {\n static TransformerName = \"reasoning\";\n enable: any;\n\n constructor(private readonly options?: TransformerOptions) {\n this.enable = this.options?.enable ?? true;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!this.enable) {\n request.thinking = {\n type: \"disabled\",\n budget_tokens: -1,\n };\n request.enable_thinking = false;\n return request;\n }\n if (request.reasoning) {\n request.thinking = {\n type: \"enabled\",\n budget_tokens: request.reasoning.max_tokens,\n };\n request.enable_thinking = true;\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (!this.enable) return response;\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // Buffer for incomplete data\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n // Process buffer function\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Process line function\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n this.logger?.debug({ line }, `Processing reason line`);\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n (data.choices?.[0]?.delta?.content ||\n data.choices?.[0]?.delta?.tool_calls) &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // Process remaining data in buffer\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // Process complete lines from buffer\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder: encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // Pass through original line if parsing fails\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class SamplingTransformer implements Transformer {\n name = \"sampling\";\n\n max_tokens: number;\n temperature: number;\n top_p: number;\n top_k: number;\n repetition_penalty: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n this.temperature = this.options?.temperature;\n this.top_p = this.options?.top_p;\n this.top_k = this.options?.top_k;\n this.repetition_penalty = this.options?.repetition_penalty;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n if (typeof this.temperature !== \"undefined\") {\n request.temperature = this.temperature;\n }\n if (typeof this.top_p !== \"undefined\") {\n request.top_p = this.top_p;\n }\n if (typeof this.top_k !== \"undefined\") {\n request.top_k = this.top_k;\n }\n if (typeof this.repetition_penalty !== \"undefined\") {\n request.repetition_penalty = this.repetition_penalty;\n }\n return request;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\r\nimport { Transformer } from \"../types/transformer\";\r\n\r\nexport class MaxCompletionTokens implements Transformer {\r\n static TransformerName = \"maxcompletiontokens\";\r\n\r\n async transformRequestIn(\r\n request: UnifiedChatRequest\r\n ): Promise {\r\n if (request.max_tokens) {\r\n request.max_completion_tokens = request.max_tokens;\r\n delete request.max_tokens;\r\n }\r\n return request;\r\n }\r\n}\r\n", "import { UnifiedChatRequest, UnifiedMessage, UnifiedTool } from \"../types/llm\";\n\n// Vertex Claude\u6D88\u606F\u63A5\u53E3\ninterface ClaudeMessage {\n role: \"user\" | \"assistant\";\n content: Array<{\n type: \"text\" | \"image\";\n text?: string;\n source?: {\n type: \"base64\";\n media_type: string;\n data: string;\n };\n }>;\n}\n\n// Vertex Claude\u5DE5\u5177\u63A5\u53E3\ninterface ClaudeTool {\n name: string;\n description: string;\n input_schema: {\n type: string;\n properties: Record;\n required?: string[];\n additionalProperties?: boolean;\n $schema?: string;\n };\n}\n\n// Vertex Claude\u8BF7\u6C42\u63A5\u53E3\ninterface VertexClaudeRequest {\n anthropic_version: \"vertex-2023-10-16\";\n messages: ClaudeMessage[];\n max_tokens: number;\n stream?: boolean;\n temperature?: number;\n top_p?: number;\n top_k?: number;\n tools?: ClaudeTool[];\n tool_choice?: \"auto\" | \"none\" | { type: \"tool\"; name: string };\n}\n\n// Vertex Claude\u54CD\u5E94\u63A5\u53E3\ninterface VertexClaudeResponse {\n content: Array<{\n type: \"text\";\n text: string;\n }>;\n id: string;\n model: string;\n role: \"assistant\";\n stop_reason: string;\n stop_sequence: null;\n type: \"message\";\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n tool_use?: Array<{\n id: string;\n name: string;\n input: Record;\n }>;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): VertexClaudeRequest {\n const messages: ClaudeMessage[] = [];\n\n for (let i = 0; i < request.messages.length; i++) {\n const message = request.messages[i];\n const isLastMessage = i === request.messages.length - 1;\n const isAssistantMessage = message.role === \"assistant\";\n\n const content: ClaudeMessage[\"content\"] = [];\n\n if (typeof message.content === \"string\") {\n // \u4FDD\u7559\u6240\u6709\u5B57\u7B26\u4E32\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\uFF0C\u56E0\u4E3A\u53EF\u80FD\u5305\u542B\u91CD\u8981\u4FE1\u606F\n content.push({\n type: \"text\",\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n message.content.forEach((item) => {\n if (item.type === \"text\") {\n // \u4FDD\u7559\u6240\u6709\u6587\u672C\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\n content.push({\n type: \"text\",\n text: item.text || \"\",\n });\n } else if (item.type === \"image_url\") {\n // \u5904\u7406\u56FE\u7247\u5185\u5BB9\n content.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: item.media_type || \"image/jpeg\",\n data: item.image_url.url,\n },\n });\n }\n });\n }\n\n // \u53EA\u8DF3\u8FC7\u5B8C\u5168\u7A7A\u7684\u975E\u6700\u540E\u4E00\u6761\u6D88\u606F\uFF08\u6CA1\u6709\u5185\u5BB9\u548C\u5DE5\u5177\u8C03\u7528\uFF09\n if (\n !isLastMessage &&\n content.length === 0 &&\n !message.tool_calls &&\n !message.content\n ) {\n continue;\n }\n\n // \u5BF9\u4E8E\u6700\u540E\u4E00\u6761 assistant \u6D88\u606F\uFF0C\u5982\u679C\u6CA1\u6709\u5185\u5BB9\u4F46\u6709\u5DE5\u5177\u8C03\u7528\uFF0C\u5219\u6DFB\u52A0\u7A7A\u5185\u5BB9\n if (\n isLastMessage &&\n isAssistantMessage &&\n content.length === 0 &&\n message.tool_calls\n ) {\n content.push({\n type: \"text\",\n text: \"\",\n });\n }\n\n messages.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content,\n });\n }\n\n const requestBody: VertexClaudeRequest = {\n anthropic_version: \"vertex-2023-10-16\",\n messages,\n max_tokens: request.max_tokens || 1000,\n stream: request.stream || false,\n ...(request.temperature && { temperature: request.temperature }),\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map((tool: UnifiedTool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (request.tool_choice) {\n if (request.tool_choice === \"auto\" || request.tool_choice === \"none\") {\n requestBody.tool_choice = request.tool_choice;\n } else if (typeof request.tool_choice === \"string\") {\n // \u5982\u679C tool_choice \u662F\u5B57\u7B26\u4E32\uFF0C\u5047\u8BBE\u662F\u5DE5\u5177\u540D\u79F0\n requestBody.tool_choice = {\n type: \"tool\",\n name: request.tool_choice,\n };\n }\n }\n\n return requestBody;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const vertexRequest = request as VertexClaudeRequest;\n\n const messages: UnifiedMessage[] = vertexRequest.messages.map((msg) => {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\" as const,\n text: item.text || \"\",\n };\n } else if (item.type === \"image\" && item.source) {\n return {\n type: \"image_url\" as const,\n image_url: {\n url: item.source.data,\n },\n media_type: item.source.media_type,\n };\n }\n return {\n type: \"text\" as const,\n text: \"\",\n };\n });\n\n return {\n role: msg.role,\n content,\n };\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model || \"claude-sonnet-4@20250514\",\n max_tokens: vertexRequest.max_tokens,\n temperature: vertexRequest.temperature,\n stream: vertexRequest.stream,\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (vertexRequest.tools && vertexRequest.tools.length > 0) {\n result.tools = vertexRequest.tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\" as const,\n properties: tool.input_schema.properties,\n required: tool.input_schema.required,\n additionalProperties: tool.input_schema.additionalProperties,\n $schema: tool.input_schema.$schema,\n },\n },\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (vertexRequest.tool_choice) {\n if (typeof vertexRequest.tool_choice === \"string\") {\n result.tool_choice = vertexRequest.tool_choice;\n } else if (vertexRequest.tool_choice.type === \"tool\") {\n result.tool_choice = vertexRequest.tool_choice.name;\n }\n }\n\n return result;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = (await response.json()) as VertexClaudeResponse;\n\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\n let tool_calls = undefined;\n if (jsonResponse.tool_use && jsonResponse.tool_use.length > 0) {\n tool_calls = jsonResponse.tool_use.map((tool) => ({\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input),\n },\n }));\n }\n\n // \u8F6C\u6362\u4E3AOpenAI\u683C\u5F0F\u7684\u54CD\u5E94\n const res = {\n id: jsonResponse.id,\n choices: [\n {\n finish_reason: jsonResponse.stop_reason || null,\n index: 0,\n message: {\n content: jsonResponse.content[0]?.text || \"\",\n role: \"assistant\",\n ...(tool_calls && { tool_calls }),\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.model,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usage.output_tokens,\n prompt_tokens: jsonResponse.usage.input_tokens,\n total_tokens:\n jsonResponse.usage.input_tokens + jsonResponse.usage.output_tokens,\n },\n };\n\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // \u5904\u7406 Anthropic \u539F\u751F\u683C\u5F0F\u7684\u6D41\u5F0F\u54CD\u5E94\n if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"text_delta\"\n ) {\n // \u8FD9\u662F Anthropic \u539F\u751F\u683C\u5F0F\uFF0C\u9700\u8981\u8F6C\u6362\u4E3A OpenAI \u683C\u5F0F\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.delta.text || \"\",\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"input_json_delta\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u7684\u53C2\u6570\u589E\u91CF\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n function: {\n arguments: chunk.delta.partial_json || \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_start\" &&\n chunk.content_block?.type === \"tool_use\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u5F00\u59CB\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n id: chunk.content_block.id,\n type: \"function\",\n function: {\n name: chunk.content_block.name,\n arguments: \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_delta\") {\n // \u5904\u7406\u6D88\u606F\u7ED3\u675F\n const res = {\n choices: [\n {\n delta: {},\n finish_reason:\n chunk.delta?.stop_reason === \"tool_use\"\n ? \"tool_calls\"\n : chunk.delta?.stop_reason === \"max_tokens\"\n ? \"length\"\n : chunk.delta?.stop_reason === \"stop_sequence\"\n ? \"content_filter\"\n : \"stop\",\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_stop\") {\n // \u53D1\u9001\u7ED3\u675F\u6807\u8BB0\n controller.enqueue(encoder.encode(`data: [DONE]\\n\\n`));\n } else {\n // \u5904\u7406\u5176\u4ED6\u683C\u5F0F\u7684\u54CD\u5E94\uFF08\u4FDD\u6301\u539F\u6709\u903B\u8F91\u4F5C\u4E3A\u540E\u5907\uFF09\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.content?.[0]?.text || \"\",\n },\n finish_reason: chunk.stop_reason?.toLowerCase() || null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n }\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/vertex-claude.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\n\n\nexport class VertexClaudeTransformer implements Transformer {\n name = \"vertex-claude\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-east5';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `/v1/projects/${projectId}/locations/${location}/publishers/anthropic/models/${request.model}:${request.stream ? \"streamRawPredict\" : \"rawPredict\"}`,\n `https://${location}-aiplatform.googleapis.com`\n ).toString(),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n };\n }\n\n async transformRequestOut(request: Record): Promise {\n return transformRequestOut(request);\n }\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest, UnifiedMessage } from \"@/types/llm\";\nimport { Transformer } from \"@/types/transformer\";\n\n/**\n * Converts content from Claude Code format (array of objects) to plain string\n * @param content - The content to convert\n * @returns The converted string content\n */\nfunction convertContentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n \n if (Array.isArray(content)) {\n return content\n .map(item => {\n if (typeof item === 'string') {\n return item;\n }\n if (typeof item === 'object' && item !== null && \n 'type' in item && item.type === 'text' && \n 'text' in item && typeof item.text === 'string') {\n return item.text;\n }\n return '';\n })\n .join('');\n }\n \n return '';\n}\n\n/**\n * Transformer class for Cerebras\n */\nexport class CerebrasTransformer implements Transformer {\n name = \"cerebras\";\n\n /**\n * Transform the request from Claude Code format to Cerebras format\n * @param request - The incoming request\n * @param provider - The LLM provider information\n * @returns The transformed request\n */\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n // Deep clone the request to avoid modifying the original\n const transformedRequest = JSON.parse(JSON.stringify(request));\n \n // IMPORTANT: Cerebras API requires a model field in the request body\n // If model is not present in the request, use the first model from provider config\n if (!transformedRequest.model && provider.models && provider.models.length > 0) {\n transformedRequest.model = provider.models[0];\n }\n \n // Handle system field at the top level - convert to system message\n if (transformedRequest.system !== undefined) {\n const systemContent = convertContentToString(transformedRequest.system);\n // Add system message at the beginning of messages array\n if (!transformedRequest.messages) {\n transformedRequest.messages = [];\n }\n transformedRequest.messages.unshift({\n role: 'system',\n content: systemContent\n });\n // Remove the top-level system field as it's now in messages\n delete transformedRequest.system;\n }\n \n // Transform messages - IMPORTANT: This must convert ALL message content to strings\n if (transformedRequest.messages && Array.isArray(transformedRequest.messages)) {\n transformedRequest.messages = transformedRequest.messages.map((message: UnifiedMessage) => {\n const transformedMessage = { ...message };\n \n // Convert content to string format for ALL messages\n if (transformedMessage.content !== undefined) {\n transformedMessage.content = convertContentToString(transformedMessage.content);\n }\n \n return transformedMessage;\n });\n }\n \n return {\n body: transformedRequest,\n config: {\n headers: {\n 'Authorization': `Bearer ${provider.apiKey}`,\n 'Content-Type': 'application/json'\n }\n }\n };\n }\n\n /**\n * Transform the response\n * @param response - The response from Cerebras\n * @returns The transformed response\n */\n async transformResponseOut(response: Response): Promise {\n // Cerebras responses should be compatible with Claude Code\n // No transformation needed\n return response;\n }\n}", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class StreamOptionsTransformer implements Transformer {\n name = \"streamoptions\";\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.stream) return request;\n request.stream_options = {\n include_usage: true,\n };\n return request;\n }\n}\n", "import { AnthropicTransformer } from \"./anthropic.transformer\";\nimport { GeminiTransformer } from \"./gemini.transformer\";\nimport { VertexGeminiTransformer } from \"./vertex-gemini.transformer\";\nimport { DeepseekTransformer } from \"./deepseek.transformer\";\nimport { TooluseTransformer } from \"./tooluse.transformer\";\nimport { OpenrouterTransformer } from \"./openrouter.transformer\";\nimport { MaxTokenTransformer } from \"./maxtoken.transformer\";\nimport { GroqTransformer } from \"./groq.transformer\";\nimport { CleancacheTransformer } from \"./cleancache.transformer\";\nimport { EnhanceToolTransformer } from \"./enhancetool.transformer\";\nimport { ReasoningTransformer } from \"./reasoning.transformer\";\nimport { SamplingTransformer } from \"./sampling.transformer\";\nimport { MaxCompletionTokens } from \"./maxcompletiontokens.transformer\";\nimport { VertexClaudeTransformer } from \"./vertex-claude.transformer\";\nimport { CerebrasTransformer } from \"./cerebras.transformer\";\nimport { StreamOptionsTransformer } from \"./streamoptions.transformer\";\n\nexport default {\n AnthropicTransformer,\n GeminiTransformer,\n VertexGeminiTransformer,\n VertexClaudeTransformer,\n DeepseekTransformer,\n TooluseTransformer,\n OpenrouterTransformer,\n MaxTokenTransformer,\n GroqTransformer,\n CleancacheTransformer,\n EnhanceToolTransformer,\n ReasoningTransformer,\n SamplingTransformer,\n MaxCompletionTokens,\n CerebrasTransformer,\n StreamOptionsTransformer\n};\n", "import { Transformer, TransformerConstructor } from \"@/types/transformer\";\nimport { ConfigService } from \"./config\";\nimport Transformers from \"@/transformer\";\nimport Module from \"node:module\";\n\ninterface TransformerConfig {\n transformers: Array<{\n name: string;\n type: \"class\" | \"module\";\n path?: string;\n options?: any;\n }>;\n}\n\nexport class TransformerService {\n private transformers: Map =\n new Map();\n\n constructor(\n private readonly configService: ConfigService,\n private readonly logger: any\n ) {}\n\n registerTransformer(name: string, transformer: Transformer): void {\n this.transformers.set(name, transformer);\n this.logger.info(\n `register transformer: ${name}${\n transformer.endPoint\n ? ` (endpoint: ${transformer.endPoint})`\n : \" (no endpoint)\"\n }`\n );\n }\n\n getTransformer(\n name: string\n ): Transformer | TransformerConstructor | undefined {\n return this.transformers.get(name);\n }\n\n getAllTransformers(): Map {\n return new Map(this.transformers);\n }\n\n getTransformersWithEndpoint(): { name: string; transformer: Transformer }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n getTransformersWithoutEndpoint(): {\n name: string;\n transformer: Transformer;\n }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (!transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n removeTransformer(name: string): boolean {\n return this.transformers.delete(name);\n }\n\n hasTransformer(name: string): boolean {\n return this.transformers.has(name);\n }\n\n async registerTransformerFromConfig(config: {\n path?: string;\n options?: any;\n }): Promise {\n try {\n if (config.path) {\n const module = require(require.resolve(config.path));\n if (module) {\n const instance = new module(config.options);\n // Set logger for transformer instance\n if (instance && typeof instance === \"object\") {\n (instance as any).logger = this.logger;\n }\n if (!instance.name) {\n throw new Error(\n `Transformer instance from ${config.path} does not have a name property.`\n );\n }\n this.registerTransformer(instance.name, instance);\n return true;\n }\n }\n return false;\n } catch (error: any) {\n this.logger.error(\n `load transformer (${config.path}) \\nerror: ${error.message}\\nstack: ${error.stack}`\n );\n return false;\n }\n }\n\n async initialize(): Promise {\n try {\n await this.registerDefaultTransformersInternal();\n await this.loadFromConfig();\n } catch (error: any) {\n this.logger.error(\n `TransformerService init error: ${error.message}\\nStack: ${error.stack}`\n );\n }\n }\n\n private async registerDefaultTransformersInternal(): Promise {\n try {\n Object.values(Transformers).forEach(\n (TransformerStatic: TransformerConstructor) => {\n if (\n \"TransformerName\" in TransformerStatic &&\n typeof TransformerStatic.TransformerName === \"string\"\n ) {\n this.registerTransformer(\n TransformerStatic.TransformerName,\n TransformerStatic\n );\n } else {\n const transformerInstance = new TransformerStatic();\n // Set logger for transformer instance\n if (\n transformerInstance &&\n typeof transformerInstance === \"object\"\n ) {\n (transformerInstance as any).logger = this.logger;\n }\n this.registerTransformer(\n transformerInstance.name!,\n transformerInstance\n );\n }\n }\n );\n } catch (error) {\n this.logger.error({ error }, \"transformer regist error:\");\n }\n }\n\n private async loadFromConfig(): Promise {\n const transformers = this.configService.get<\n TransformerConfig[\"transformers\"]\n >(\"transformers\", []);\n for (const transformer of transformers) {\n await this.registerTransformerFromConfig(transformer);\n }\n }\n}\n"], + "mappings": "82BAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CACAA,GAAO,QAAQ,gBAAkB,0CACjCA,GAAO,QAAQ,SAAW,s7NAC1BA,GAAO,QAAQ,YAAc,u2QCH7B,IAAAC,GAAAC,EAAA,CAAAC,GAAAC,KAAA,KAAMC,GAAU,KAEhBD,GAAO,QAAU,CACb,iBAAkBE,EAAG,CACjB,OAAO,OAAOA,GAAM,UAAYD,GAAQ,gBAAgB,KAAKC,CAAC,CAClE,EAEA,cAAeA,EAAG,CACd,OAAO,OAAOA,GAAM,WACfA,GAAK,KAAOA,GAAK,KACrBA,GAAK,KAAOA,GAAK,KACjBA,IAAM,KAASA,IAAM,KACtBD,GAAQ,SAAS,KAAKC,CAAC,EAE3B,EAEA,iBAAkBA,EAAG,CACjB,OAAO,OAAOA,GAAM,WACfA,GAAK,KAAOA,GAAK,KACrBA,GAAK,KAAOA,GAAK,KACjBA,GAAK,KAAOA,GAAK,KACjBA,IAAM,KAASA,IAAM,KACrBA,IAAM,UAAcA,IAAM,UAC3BD,GAAQ,YAAY,K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OAASE,EAAK,CACZ,OAAAJ,EAAI,IAAI,MAAM,oCAAqCI,CAAG,EAC/CN,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,MAAO,uBAAwB,CAAC,CAChE,CACF,CACF,EAEA,KAAK,IAAI,SAASO,EAAiB,EAEnC,IAAMC,EAAU,MAAM,KAAK,IAAI,OAAO,CACpC,KAAM,SAAS,KAAK,cAAc,IAAI,MAAM,GAAK,OAAQ,EAAE,EAC3D,KAAM,KAAK,cAAc,IAAI,MAAM,GAAK,WAC1C,CAAC,EAED,KAAK,IAAI,IAAI,KAAK,0CAAmCA,CAAO,EAAE,EAE9D,IAAMC,EAAW,MAAOC,GAAmB,CACzC,KAAK,IAAI,IAAI,KAAK,YAAYA,CAAM,+BAA+B,EACnE,MAAM,KAAK,IAAI,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,EAEA,QAAQ,GAAG,SAAU,IAAMD,EAAS,QAAQ,CAAC,EAC7C,QAAQ,GAAG,UAAW,IAAMA,EAAS,SAAS,CAAC,CACjD,OAASE,EAAO,CACd,KAAK,IAAI,IAAI,MAAM,0BAA0BA,CAAK,EAAE,EACpD,QAAQ,KAAK,CAAC,CAChB,CACF,CACF,EAGOC,GAAQtB", + "names": ["require_unicode", "__commonJSMin", "exports", "module", "require_util", "__commonJSMin", "exports", "module", "unicode", "c", "require_parse", "__commonJSMin", "exports", "module", "util", "source", "parseState", "stack", "pos", "line", "column", "token", "key", "root", "text", "reviver", "lex", "parseStates", "internalize", "holder", "name", "value", "i", "replacement", "lexState", "buffer", "doubleQuote", "sign", "c", "peek", "lexStates", "read", "newToken", "invalidChar", "literal", "u", "unicodeEscape", "invalidIdentifier", "escape", "separatorChar", "type", "s", "hexEscape", "count", "invalidEOF", "push", "pop", "parent", "current", "syntaxError", "formatChar", "replacements", "hexString", "message", "err", "require_stringify", "__commonJSMin", "exports", "module", "util", "value", "replacer", "space", "stack", "indent", "propertyList", "replacerFunc", "gap", "quote", "v", "item", "serializeProperty", "key", "holder", "quoteString", "serializeArray", "serializeObject", "quotes", "replacements", "product", "i", "c", "hexString", "quoteChar", "a", "b", "stepback", "keys", "partial", "propertyString", "member", "serializeKey", "final", "properties", "separator", "firstChar", "require_lib", "__commonJSMin", "exports", "module", "parse", "stringify", "JSON5", "require_extend", "__commonJSMin", "exports", "module", "hasOwn", "toStr", "defineProperty", "gOPD", "isArray", "arr", "isPlainObject", "obj", "hasOwnConstructor", "hasIsPrototypeOf", "key", "setProperty", "target", "options", "getProperty", "name", "extend", "src", "copy", "copyIsArray", "clone", "i", "length", "deep", "require_package", "__commonJSMin", "exports", "module", "pkg", "module", "exports", "defaultErrorRedactor", "extend_1", "__importDefault", "util_cjs_1", "pkg", "GaxiosError", "_GaxiosError", "instance", "message", "config", "response", "cause", "translateData", "res", "defaultErrorMessage", "status", "code", "errorMessages", "e", "responseType", "data", "REDACT", "redactHeaders", "headers", "_", "key", "redactString", "obj", "text", "redactObject", "exports", "getRetryConfig", "err", "config", "getConfig", "retryRanges", "shouldRetryRequest", "delay", "getNextRetryDelay", "backoff", "resolve", "isInRange", "min", "max", "status", "calculatedDelay", "maxAllowableDelay", "GaxiosInterceptorManager", "exports", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "ns", "matchesTemplate", "search", "template", "searchIndex", "templateIndex", "starIndex", "matchIndex", "name", "skip", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "require_has_flag", "__commonJSMin", "exports", "module", "flag", "argv", "prefix", "pos", "terminatorPos", "require_supports_color", "__commonJSMin", "exports", "module", "os", "hasFlag", "env", "forceColor", "translateLevel", "level", "supportsColor", "stream", "min", "osRelease", "sign", "version", "getSupportLevel", "require_node", "__commonJSMin", "exports", "module", "tty", "util", "init", "log", "formatArgs", "save", "load", "useColors", "supportsColor", "key", "obj", "prop", "_", "k", "val", "args", "name", "c", "colorCode", "prefix", "getDate", "namespaces", "debug", "keys", "i", "formatters", "v", "str", "require_src", "__commonJSMin", "exports", "module", "http", "__importStar", "https", "toBuffer", "stream", "length", "chunks", "chunk", "exports", "json", "str", "_err", "err", "req", "url", "opts", "promise", "resolve", "reject", "net", "__importStar", "http", "https_1", "__exportStar", "exports", "INTERNAL", "Agent", "opts", "options", "stack", "l", "name", "fakeSocket", "socket", "sockets", "index", "req", "cb", "connectOpts", "err", "v", "debug_1", "__importDefault", "debug", "parseProxyResponse", "socket", "resolve", "reject", "buffersLength", "buffers", "read", "b", "ondata", "cleanup", "onend", "onerror", "err", "buffered", "endOfHeaders", "headerParts", "firstLine", "firstLineParts", "statusCode", "statusText", "headers", "header", "firstColon", "key", "value", "current", "exports", "net", "__importStar", "tls", "assert_1", "__importDefault", "debug_1", "agent_base_1", "url_1", "parse_proxy_response_1", "debug", "setServernameFromNonIpHost", "options", "HttpsProxyAgent", "proxy", "opts", "host", "port", "omit", "req", "socket", "headers", "payload", "auth", "name", "proxyResponsePromise", "connect", "buffered", "resume", "fakeSocket", "s", "exports", "obj", "keys", "ret", "key", "dataUriToBuffer", "uri", "firstComma", "meta", "charset", "base64", "type", "typeFull", "i", "encoding", "data", "buffer", "dist_default", "init_dist", "__esmMin", "noop", "typeIsObject", "x", "rethrowAssertionErrorRejection", "setFunctionName", "fn", "name", "originalPromise", "originalPromiseThen", "originalPromiseReject", "newPromise", "executor", "promiseResolvedWith", "value", "resolve", "promiseRejectedWith", "reason", "PerformPromiseThen", "promise", "onFulfilled", "onRejected", "uponPromise", "uponFulfillment", "uponRejection", "transformPromiseWith", "fulfillmentHandler", "rejectionHandler", "setPromiseIsHandledToTrue", "_queueMicrotask", "callback", "resolvedPromise", "cb", "reflectCall", "F", "V", "args", "promiseCall", "QUEUE_MAX_ARRAY_SIZE", "SimpleQueue", "element", "oldBack", "newBack", "oldFront", "newFront", "oldCursor", "newCursor", "elements", "i", "node", "front", "cursor", "AbortSteps", "ErrorSteps", "CancelSteps", "PullSteps", "ReleaseSteps", "ReadableStreamReaderGenericInitialize", "reader", "stream", "defaultReaderClosedPromiseInitialize", "defaultReaderClosedPromiseInitializeAsResolved", "defaultReaderClosedPromiseInitializeAsRejected", "ReadableStreamReaderGenericCancel", "ReadableStreamCancel", "ReadableStreamReaderGenericRelease", "defaultReaderClosedPromiseReject", "defaultReaderClosedPromiseResetToRejected", "readerLockException", "reject", "defaultReaderClosedPromiseResolve", "NumberIsFinite", "MathTrunc", "v", "isDictionary", "assertDictionary", "obj", "context", "assertFunction", "isObject", "assertObject", "assertRequiredArgument", "position", "assertRequiredField", "field", "convertUnrestrictedDouble", "censorNegativeZero", "integerPart", "convertUnsignedLongLongWithEnforceRange", "upperBound", "assertReadableStream", "IsReadableStream", "AcquireReadableStreamDefaultReader", "ReadableStreamDefaultReader", "ReadableStreamAddReadRequest", "readRequest", "ReadableStreamFulfillReadRequest", "chunk", "done", "ReadableStreamGetNumReadRequests", "ReadableStreamHasDefaultReader", "IsReadableStreamDefaultReader", "IsReadableStreamLocked", "defaultReaderBrandCheckException", "resolvePromise", "rejectPromise", "ReadableStreamDefaultReaderRead", "e", "ReadableStreamDefaultReaderRelease", "ReadableStreamDefaultReaderErrorReadRequests", "readRequests", "AsyncIteratorPrototype", "ReadableStreamAsyncIteratorImpl", "preventCancel", "nextSteps", "returnSteps", "queueMicrotask", "result", "ReadableStreamAsyncIteratorPrototype", "IsReadableStreamAsyncIterator", "streamAsyncIteratorBrandCheckException", "AcquireReadableStreamAsyncIterator", "impl", "iterator", "NumberIsNaN", "CreateArrayFromList", "CopyDataBlockBytes", "dest", "destOffset", "src", "srcOffset", "n", "TransferArrayBuffer", "O", "buffer", "IsDetachedBuffer", "ArrayBufferSlice", "begin", "end", "length", "slice", "GetMethod", "receiver", "prop", "func", "CreateAsyncFromSyncIterator", "syncIteratorRecord", "syncIterable", "asyncIterator", "nextMethod", "SymbolAsyncIterator", "_c", "_a", "_b", "GetIterator", "hint", "method", "syncMethod", "IteratorNext", "iteratorRecord", "IteratorComplete", "iterResult", "IteratorValue", "IsNonNegativeNumber", "CloneAsUint8Array", "DequeueValue", "container", "pair", "EnqueueValueWithSize", "size", "PeekQueueValue", "ResetQueue", "isDataViewConstructor", "ctor", "isDataView", "view", "arrayBufferViewElementSize", "ReadableStreamBYOBRequest", "IsReadableStreamBYOBRequest", "byobRequestBrandCheckException", "bytesWritten", "ReadableByteStreamControllerRespond", "ReadableByteStreamControllerRespondWithNewView", "ReadableByteStreamController", "IsReadableByteStreamController", "byteStreamControllerBrandCheckException", "ReadableByteStreamControllerGetBYOBRequest", "ReadableByteStreamControllerGetDesiredSize", "state", "ReadableByteStreamControllerClose", "ReadableByteStreamControllerEnqueue", "ReadableByteStreamControllerError", "ReadableByteStreamControllerClearPendingPullIntos", "ReadableByteStreamControllerClearAlgorithms", "ReadableByteStreamControllerFillReadRequestFromQueue", "autoAllocateChunkSize", "bufferE", "pullIntoDescriptor", "ReadableByteStreamControllerCallPullIfNeeded", "firstPullInto", "controller", "ReadableByteStreamControllerShouldCallPull", "pullPromise", "ReadableByteStreamControllerInvalidateBYOBRequest", "ReadableByteStreamControllerCommitPullIntoDescriptor", "filledView", "ReadableByteStreamControllerConvertPullIntoDescriptor", "ReadableStreamFulfillReadIntoRequest", "bytesFilled", "elementSize", "ReadableByteStreamControllerEnqueueChunkToQueue", "byteOffset", "byteLength", "ReadableByteStreamControllerEnqueueClonedChunkToQueue", "clonedChunk", "cloneE", "ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue", "firstDescriptor", "ReadableByteStreamControllerShiftPendingPullInto", "ReadableByteStreamControllerFillPullIntoDescriptorFromQueue", "maxBytesToCopy", "maxBytesFilled", "totalBytesToCopyRemaining", "ready", "remainderBytes", "maxAlignedBytes", "queue", "headOfQueue", "bytesToCopy", "destStart", "ReadableByteStreamControllerFillHeadPullIntoDescriptor", "ReadableByteStreamControllerHandleQueueDrain", "ReadableStreamClose", "ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue", "ReadableByteStreamControllerProcessReadRequestsUsingQueue", "ReadableByteStreamControllerPullInto", "min", "readIntoRequest", "minimumFill", "ReadableStreamAddReadIntoRequest", "emptyView", "ReadableByteStreamControllerRespondInClosedState", "ReadableStreamHasBYOBReader", "ReadableStreamGetNumReadIntoRequests", "ReadableByteStreamControllerRespondInReadableState", "remainderSize", "ReadableByteStreamControllerRespondInternal", "firstPendingPullInto", "transferredBuffer", "transferredView", "ReadableStreamError", "entry", "byobRequest", "SetUpReadableStreamBYOBRequest", "viewByteLength", "SetUpReadableByteStreamController", "startAlgorithm", "pullAlgorithm", "cancelAlgorithm", "highWaterMark", "startResult", "r", "SetUpReadableByteStreamControllerFromUnderlyingSource", "underlyingByteSource", "request", "convertReaderOptions", "options", "mode", "convertReadableStreamReaderMode", "convertByobReadOptions", "AcquireReadableStreamBYOBReader", "ReadableStreamBYOBReader", "IsReadableStreamBYOBReader", "byobReaderBrandCheckException", "rawOptions", "ReadableStreamBYOBReaderRead", "ReadableStreamBYOBReaderRelease", "ReadableStreamBYOBReaderErrorReadIntoRequests", "readIntoRequests", "ExtractHighWaterMark", "strategy", "defaultHWM", "ExtractSizeAlgorithm", "convertQueuingStrategy", "init", "convertQueuingStrategySize", "convertUnderlyingSink", "original", "abort", "close", "start", "type", "write", "convertUnderlyingSinkAbortCallback", "convertUnderlyingSinkCloseCallback", "convertUnderlyingSinkStartCallback", "convertUnderlyingSinkWriteCallback", "assertWritableStream", "IsWritableStream", "isAbortSignal", "supportsAbortController", "createAbortController", "WritableStream", "rawUnderlyingSink", "rawStrategy", "underlyingSink", "InitializeWritableStream", "sizeAlgorithm", "SetUpWritableStreamDefaultControllerFromUnderlyingSink", "streamBrandCheckException", "IsWritableStreamLocked", "WritableStreamAbort", "WritableStreamCloseQueuedOrInFlight", "WritableStreamClose", "AcquireWritableStreamDefaultWriter", "WritableStreamDefaultWriter", "CreateWritableStream", "writeAlgorithm", "closeAlgorithm", "abortAlgorithm", "WritableStreamDefaultController", "SetUpWritableStreamDefaultController", "wasAlreadyErroring", "WritableStreamStartErroring", "closeRequest", "writer", "defaultWriterReadyPromiseResolve", "WritableStreamDefaultControllerClose", "WritableStreamAddWriteRequest", "writeRequest", "WritableStreamDealWithRejection", "error", "WritableStreamFinishErroring", "WritableStreamDefaultWriterEnsureReadyPromiseRejected", "WritableStreamHasOperationMarkedInFlight", "storedError", "WritableStreamRejectCloseAndClosedPromiseIfNeeded", "abortRequest", "WritableStreamFinishInFlightWrite", "WritableStreamFinishInFlightWriteWithError", "WritableStreamFinishInFlightClose", "defaultWriterClosedPromiseResolve", "WritableStreamFinishInFlightCloseWithError", "WritableStreamMarkCloseRequestInFlight", "WritableStreamMarkFirstWriteRequestInFlight", "defaultWriterClosedPromiseReject", "WritableStreamUpdateBackpressure", "backpressure", "defaultWriterReadyPromiseReset", "defaultWriterReadyPromiseInitialize", "defaultWriterReadyPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitialize", "defaultWriterReadyPromiseInitializeAsRejected", "defaultWriterClosedPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitializeAsRejected", "IsWritableStreamDefaultWriter", "defaultWriterBrandCheckException", "defaultWriterLockException", "WritableStreamDefaultWriterGetDesiredSize", "WritableStreamDefaultWriterAbort", "WritableStreamDefaultWriterClose", "WritableStreamDefaultWriterRelease", "WritableStreamDefaultWriterWrite", "WritableStreamDefaultWriterCloseWithErrorPropagation", "WritableStreamDefaultWriterEnsureClosedPromiseRejected", "defaultWriterClosedPromiseResetToRejected", "defaultWriterReadyPromiseReject", "defaultWriterReadyPromiseResetToRejected", "WritableStreamDefaultControllerGetDesiredSize", "releasedError", "chunkSize", "WritableStreamDefaultControllerGetChunkSize", "WritableStreamDefaultControllerWrite", "closeSentinel", "IsWritableStreamDefaultController", "defaultControllerBrandCheckException", "WritableStreamDefaultControllerError", "WritableStreamDefaultControllerClearAlgorithms", "WritableStreamDefaultControllerGetBackpressure", "startPromise", "WritableStreamDefaultControllerAdvanceQueueIfNeeded", "chunkSizeE", "WritableStreamDefaultControllerErrorIfNeeded", "enqueueE", "WritableStreamDefaultControllerProcessClose", "WritableStreamDefaultControllerProcessWrite", "sinkClosePromise", "sinkWritePromise", "getGlobals", "globals", "isDOMExceptionConstructor", "getFromGlobal", "createPolyfill", "message", "DOMException", "ReadableStreamPipeTo", "source", "preventClose", "preventAbort", "signal", "shuttingDown", "currentWrite", "actions", "shutdownWithAction", "action", "pipeLoop", "resolveLoop", "rejectLoop", "next", "pipeStep", "resolveRead", "rejectRead", "isOrBecomesErrored", "shutdown", "isOrBecomesClosed", "destClosed", "waitForWritesToFinish", "oldCurrentWrite", "originalIsError", "originalError", "doTheRest", "finalize", "newError", "isError", "ReadableStreamDefaultController", "IsReadableStreamDefaultController", "ReadableStreamDefaultControllerGetDesiredSize", "ReadableStreamDefaultControllerCanCloseOrEnqueue", "ReadableStreamDefaultControllerClose", "ReadableStreamDefaultControllerEnqueue", "ReadableStreamDefaultControllerError", "ReadableStreamDefaultControllerClearAlgorithms", "ReadableStreamDefaultControllerCallPullIfNeeded", "ReadableStreamDefaultControllerShouldCallPull", "ReadableStreamDefaultControllerHasBackpressure", "SetUpReadableStreamDefaultController", "SetUpReadableStreamDefaultControllerFromUnderlyingSource", "underlyingSource", "ReadableStreamTee", "cloneForBranch2", "ReadableByteStreamTee", "ReadableStreamDefaultTee", "reading", "readAgain", "canceled1", "canceled2", "reason1", "reason2", "branch1", "branch2", "resolveCancelPromise", "cancelPromise", "chunk1", "chunk2", "cancel1Algorithm", "compositeReason", "cancelResult", "cancel2Algorithm", "CreateReadableStream", "readAgainForBranch1", "readAgainForBranch2", "forwardReaderError", "thisReader", "pullWithDefaultReader", "pull1Algorithm", "pull2Algorithm", "pullWithBYOBReader", "forBranch2", "byobBranch", "otherBranch", "byobCanceled", "otherCanceled", "CreateReadableByteStream", "isReadableStreamLike", "ReadableStreamFrom", "ReadableStreamFromDefaultReader", "ReadableStreamFromIterable", "asyncIterable", "nextResult", "nextPromise", "returnMethod", "returnResult", "returnPromise", "readPromise", "readResult", "convertUnderlyingDefaultOrByteSource", "cancel", "pull", "convertUnderlyingSourceCancelCallback", "convertUnderlyingSourcePullCallback", "convertUnderlyingSourceStartCallback", "convertReadableStreamType", "convertIteratorOptions", "convertPipeOptions", "assertAbortSignal", "convertReadableWritablePair", "readable", "writable", "ReadableStream", "rawUnderlyingSource", "InitializeReadableStream", "rawTransform", "transform", "destination", "branches", "sourceCancelPromise", "convertQueuingStrategyInit", "byteLengthSizeFunction", "ByteLengthQueuingStrategy", "IsByteLengthQueuingStrategy", "byteLengthBrandCheckException", "countSizeFunction", "CountQueuingStrategy", "IsCountQueuingStrategy", "countBrandCheckException", "convertTransformer", "flush", "readableType", "writableType", "convertTransformerCancelCallback", "convertTransformerFlushCallback", "convertTransformerStartCallback", "convertTransformerTransformCallback", "TransformStream", "rawTransformer", "rawWritableStrategy", "rawReadableStrategy", "writableStrategy", "readableStrategy", "transformer", "readableHighWaterMark", "readableSizeAlgorithm", "writableHighWaterMark", "writableSizeAlgorithm", "startPromise_resolve", "InitializeTransformStream", "SetUpTransformStreamDefaultControllerFromTransformer", "IsTransformStream", "TransformStreamDefaultSinkWriteAlgorithm", "TransformStreamDefaultSinkAbortAlgorithm", "TransformStreamDefaultSinkCloseAlgorithm", "TransformStreamDefaultSourcePullAlgorithm", "TransformStreamDefaultSourceCancelAlgorithm", "TransformStreamSetBackpressure", "TransformStreamError", "TransformStreamErrorWritableAndUnblockWrite", "TransformStreamDefaultControllerClearAlgorithms", "TransformStreamUnblockWrite", "TransformStreamDefaultController", "IsTransformStreamDefaultController", "readableController", "TransformStreamDefaultControllerEnqueue", "TransformStreamDefaultControllerError", "TransformStreamDefaultControllerTerminate", "SetUpTransformStreamDefaultController", "transformAlgorithm", "flushAlgorithm", "transformResultE", "TransformStreamDefaultControllerPerformTransform", "transformPromise", "backpressureChangePromise", "defaultControllerFinishPromiseReject", "defaultControllerFinishPromiseResolve", "flushPromise", "require_streams", "__commonJSMin", "process", "emitWarning", "error", "Blob", "params", "position", "blob", "ctrl", "buffer", "toIterator", "parts", "clone", "part", "position", "end", "size", "POOL_SIZE", "chunk", "b", "buffer", "import_streams", "_Blob", "Blob", "fetch_blob_default", "init_fetch_blob", "__esmMin", "#parts", "#type", "#size", "#endings", "blobParts", "options", "encoder", "element", "type", "decoder", "str", "data", "offset", "it", "ctrl", "start", "relativeStart", "relativeEnd", "span", "added", "blob", "object", "_File", "File", "file_default", "init_file", "__esmMin", "init_fetch_blob", "fetch_blob_default", "#lastModified", "#name", "fileBits", "fileName", "options", "lastModified", "object", "formDataToBlob", "F", "B", "fetch_blob_default", "b", "r", "c", "p", "v", "n", "e", "t", "i", "h", "m", "f", "x", "FormData", "init_esm_min", "__esmMin", "init_fetch_blob", "init_file", "a", "file_default", "#d", "o", "l", "d", "FetchBaseError", "init_base", "__esmMin", "message", "type", "FetchError", "init_fetch_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "systemError", "NAME", "isURLSearchParameters", "isBlob", "isAbortSignal", "isDomainOrSubdomain", "isSameProtocol", "init_is", "__esmMin", "object", "destination", "original", "orig", "dest", "require_node_domexception", "__commonJSMin", "exports", "module", "MessageChannel", "port", "ab", "err", "statSync", "createReadStream", "fs", "basename", "import_node_domexception", "stat", "blobFromSync", "blobFrom", "fileFrom", "fileFromSync", "fromBlob", "fromFile", "BlobDataItem", "init_from", "__esmMin", "init_file", "init_fetch_blob", "path", "type", "fetch_blob_default", "file_default", "_BlobDataItem", "#path", "#start", "options", "start", "end", "mtimeMs", "DOMException", "multipart_parser_exports", "__export", "toFormData", "_fileName", "headerValue", "m", "match", "filename", "code", "Body", "ct", "parser", "MultipartParser", "headerField", "entryValue", "entryName", "contentType", "entryChunks", "formData", "FormData", "onPartData", "ui8a", "decoder", "appendToFile", "appendFileToFormData", "file", "file_default", "appendEntryToFormData", "chunk", "s", "S", "f", "F", "LF", "CR", "SPACE", "HYPHEN", "COLON", "A", "Z", "lower", "noop", "init_multipart_parser", "__esmMin", "init_from", "init_esm_min", "c", "boundary", "i", "data", "length_", "previousIndex", "lookbehind", "boundaryChars", "index", "state", "flags", "boundaryLength", "boundaryEnd", "bufferLength", "cl", "mark", "name", "clear", "callback", "callbackSymbol", "start", "end", "dataCallback", "markSymbol", "_lookbehind", "Stream", "PassThrough", "types", "deprecate", "promisify", "Buffer", "consumeBody", "data", "INTERNALS", "body", "accum", "accumBytes", "chunk", "error", "FetchError", "FetchBaseError", "c", "pipeline", "Body", "clone", "getNonSpecFormDataBoundary", "extractContentType", "getTotalBytes", "writeToStream", "init_body", "__esmMin", "init_fetch_blob", "init_esm_min", "init_fetch_error", "init_base", "init_is", "size", "boundary", "isURLSearchParameters", "isBlob", "FormData", "formDataToBlob", "stream", "error_", "buffer", "byteOffset", "byteLength", "ct", "formData", "parameters", "name", "value", "toFormData", "buf", "fetch_blob_default", "text", "instance", "highWaterMark", "p1", "p2", "request", "dest", "types", "http", "fromRawHeaders", "headers", "Headers", "result", "value", "index", "array", "name", "validateHeaderName", "validateHeaderValue", "init_headers", "__esmMin", "error", "_Headers", "init", "raw", "values", "method", "pair", "target", "p", "receiver", "callback", "thisArg", "key", "property", "redirectStatus", "isRedirect", "init_is_redirect", "__esmMin", "code", "INTERNALS", "Response", "init_response", "__esmMin", "init_headers", "init_body", "init_is_redirect", "_Response", "Body", "body", "options", "status", "headers", "Headers", "contentType", "extractContentType", "clone", "url", "isRedirect", "response", "data", "init", "getSearch", "init_get_search", "__esmMin", "parsedURL", "lastOffset", "hash", "isIP", "stripURLForUseAsAReferrer", "url", "originOnly", "validateReferrerPolicy", "referrerPolicy", "ReferrerPolicy", "isOriginPotentiallyTrustworthy", "hostIp", "hostIPVersion", "isUrlPotentiallyTrustworthy", "determineRequestsReferrer", "request", "referrerURLCallback", "referrerOriginCallback", "policy", "referrerSource", "referrerURL", "referrerOrigin", "currentURL", "parseReferrerPolicyFromHeader", "headers", "policyTokens", "token", "DEFAULT_REFERRER_POLICY", "init_referrer", "__esmMin", "formatUrl", "deprecate", "INTERNALS", "isRequest", "doBadDataWarn", "Request", "getNodeRequestOptions", "init_request", "__esmMin", "init_headers", "init_body", "init_is", "init_get_search", "init_referrer", "object", "_Request", "Body", "input", "init", "parsedURL", "method", "inputBody", "clone", "headers", "Headers", "contentType", "extractContentType", "signal", "isAbortSignal", "referrer", "parsedReferrer", "referrerPolicy", "validateReferrerPolicy", "request", "contentLengthValue", "totalBytes", "getTotalBytes", "DEFAULT_REFERRER_POLICY", "determineRequestsReferrer", "agent", "search", "getSearch", "options", "AbortError", "init_abort_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "src_exports", "__export", "AbortError", "fetch_blob_default", "FetchError", "file_default", "FormData", "Headers", "Request", "Response", "blobFrom", "blobFromSync", "fetch", "fileFrom", "fileFromSync", "isRedirect", "http", "https", "zlib", "Stream", "PassThrough", "pump", "Buffer", "url", "options_", "resolve", "reject", "request", "parsedURL", "options", "getNodeRequestOptions", "supportedSchemas", "data", "dist_default", "response", "send", "signal", "abort", "error", "abortAndFinalize", "finalize", "request_", "fixResponseChunkedTransferBadEnding", "s", "endedWithEventsCount", "hadError", "response_", "headers", "fromRawHeaders", "location", "locationURL", "requestOptions", "clone", "isDomainOrSubdomain", "isSameProtocol", "name", "responseReferrerPolicy", "parseReferrerPolicyFromHeader", "body", "responseOptions", "codings", "zlibOptions", "raw", "chunk", "writeToStream", "errorCallback", "LAST_CHUNK", "isChunkedTransfer", "properLastChunkReceived", "previousChunk", "socket", "onSocketClose", "onData", "buf", "init_src", "__esmMin", "init_dist", "init_body", "init_response", "init_headers", "init_request", "init_fetch_error", "init_abort_error", "init_is_redirect", "init_esm_min", "init_is", "init_referrer", "init_from", "extend_1", "__importDefault", "https_1", "common_js_1", "retry_js_1", "stream_1", "interceptor_js_1", "randomUUID", "Gaxios", "defaults", "args", "input", "init", "url", "headers", "_a", "opts", "prepared", "#prepareRequest", "#applyRequestInterceptors", "#applyResponseInterceptors", "config", "fetchImpl", "#getFetch", "preparedOpts", "res", "data", "translatedResponse", "response", "chunk", "errorInfo", "e", "err", "shouldRetry", "#appendTimeoutToSignal", "#urlMayUseProxy", "noProxy", "candidate", "noProxyList", "noProxyEnvList", "rule", "cleanedRule", "options", "promiseChain", "interceptor", "preparedHeaders", "additionalQueryParams", "prefix", "key", "value", "shouldDirectlyPassData", "boundary", "proxy", "HttpsProxyAgent", "#getProxyAgent", "timeoutSignal", "status", "contentType", "multipartOptions", "finale", "currentPart", "partContentType", "#proxyAgent", "#fetch", "hasWindow", "base", "append", "exports", "exports", "request", "gaxios_js_1", "common_js_1", "__exportStar", "opts", "require_bignumber", "__commonJSMin", "exports", "module", "globalObject", "BigNumber", "isNumeric", "mathceil", "mathfloor", "bignumberError", "tooManyDigits", "BASE", "LOG_BASE", "MAX_SAFE_INTEGER", "POWS_TEN", "SQRT_BASE", "MAX", "clone", "configObject", "div", "convertBase", "parseNumeric", "P", "ONE", "DECIMAL_PLACES", "ROUNDING_MODE", "TO_EXP_NEG", "TO_EXP_POS", "MIN_EXP", "MAX_EXP", "CRYPTO", "MODULO_MODE", "POW_PRECISION", "FORMAT", "ALPHABET", "alphabetHasNormalDecimalDigits", "v", "b", "alphabet", "c", "caseChanged", "e", "i", "isNum", "len", "str", "x", "intCheck", "round", "obj", "p", "n", "s", "out", "maxOrMin", "pow2_53", "random53bitInt", "dp", "a", "k", "rand", "args", "sum", "decimal", "toBaseOut", "baseIn", "baseOut", "j", "arr", "arrL", "sign", "callerIsToString", "d", "r", "xc", "y", "rm", "toFixedPoint", "coeffToString", "multiply", "base", "m", "temp", "xlo", "xhi", "carry", "klo", "khi", "compare", "aL", "bL", "cmp", "subtract", "more", "prod", "prodL", "q", "qc", "rem", "remL", "rem0", "xi", "xL", "yc0", "yL", "yz", "yc", "bitFloor", "format", "id", "c0", "ne", "toExponential", "normalise", "basePrefix", "dotAfter", "dotBefore", "isInfinityOrNaN", "whitespaceOrPlus", "p1", "p2", "sd", "ni", "rd", "pows10", "valueOf", "half", "isModExp", "nIsBig", "nIsNeg", "nIsOdd", "isOdd", "t", "xLTy", "xe", "ye", "xcL", "ycL", "ylo", "yhi", "zc", "sqrtBase", "rep", "g1", "g2", "groupSeparator", "intPart", "fractionPart", "isNeg", "intDigits", "md", "d0", "d1", "d2", "exp", "n0", "n1", "z", "l", "min", "max", "name", "zs", "require_stringify", "__commonJSMin", "exports", "module", "BigNumber", "JSON", "f", "n", "cx", "escapable", "gap", "indent", "meta", "rep", "quote", "string", "a", "c", "str", "key", "holder", "i", "k", "v", "length", "mind", "partial", "value", "isBigNumber", "replacer", "space", "require_parse", "__commonJSMin", "exports", "module", "BigNumber", "suspectProtoRx", "suspectConstructorRx", "json_parse", "options", "_options", "at", "ch", "escapee", "text", "error", "m", "next", "c", "number", "string", "hex", "i", "uffff", "startAt", "white", "word", "value", "array", "object", "key", "source", "reviver", "result", "walk", "holder", "k", "v", "require_json_bigint", "__commonJSMin", "exports", "module", "json_stringify", "json_parse", "options", "exports", "isGoogleCloudServerless", "isGoogleComputeEngineLinux", "isGoogleComputeEngineMACAddress", "isGoogleComputeEngine", "detectGCPResidency", "fs_1", "os_1", "GCE_MAC_ADDRESS_REGEX", "biosVendor", "interfaces", "item", "mac", "Colours", "_Colours", "stream", "exports", "exports", "getNodeBackend", "getDebugBackend", "getStructuredBackend", "setBackend", "log", "events_1", "process", "__importStar", "util", "colours_1", "LogSeverity", "AdhocDebugLogger", "namespace", "upstream", "event", "listener", "args", "fields", "severity", "DebugLogBackendBase", "nodeFlag", "_a", "logger", "e", "NodeBackend", "nscolour", "pid", "level", "msg", "filteredFields", "fieldsJson", "fieldsColour", "regexp", "DebugBackend", "pkg", "debugLogger", "existingFilters", "debugPkg", "StructuredBackend", "json", "jsonString", "loggerCache", "cachedBackend", "backend", "parent", "existing", "previousBackend", "__exportStar", "exports", "exports", "instance", "project", "universe", "bulk", "isAvailable", "resetIsAvailableCache", "getGCPResidency", "setGCPResidency", "requestTimeout", "gaxios_1", "jsonBigint", "gcp_residency_1", "logger", "__importStar", "log", "getBaseUrl", "baseUrl", "validate", "options", "key", "metadataAccessor", "type", "noResponseRetries", "fastFail", "headers", "metadataKey", "params", "value", "requestMethod", "fastFailMetadataRequest", "req", "res", "metadataFlavor", "secondaryOptions", "r1", "r2", "properties", "r", "item", "detectGCPAvailableRetries", "cachedIsAvailableResponse", "e", "err", "code", "__exportStar", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_shared", "__commonJSMin", "exports", "fromArrayBufferToHex", "arrayBuffer", "byte", "require_crypto", "__commonJSMin", "exports", "base64js", "shared_1", "BrowserCrypto", "_BrowserCrypto", "str", "inputBuffer", "outputBuffer", "count", "array", "base64", "pubkey", "data", "signature", "algo", "dataArray", "signatureArray", "cryptoKey", "privateKey", "result", "uint8array", "text", "key", "msg", "rawKey", "enc", "require_crypto", "__commonJSMin", "exports", "crypto", "NodeCrypto", "str", "count", "pubkey", "data", "signature", "verifier", "privateKey", "signer", "base64", "text", "key", "msg", "cryptoKey", "toBuffer", "toArrayBuffer", "buffer", "arrayBuffer", "require_crypto", "__commonJSMin", "exports", "__createBinding", "o", "m", "k", "k2", "desc", "__exportStar", "p", "createCrypto", "hasBrowserCrypto", "crypto_1", "crypto_2", "require_safe_buffer", "__commonJSMin", "exports", "module", "buffer", "Buffer", "copyProps", "src", "dst", "key", "SafeBuffer", "arg", "encodingOrOffset", "length", "size", "fill", "encoding", "buf", "require_param_bytes_for_alg", "__commonJSMin", "exports", "module", "getParamSize", "keySize", "result", "paramBytesForAlg", "getParamBytesForAlg", "alg", "paramBytes", "require_ecdsa_sig_formatter", "__commonJSMin", "exports", "module", "Buffer", "getParamBytesForAlg", "MAX_OCTET", "CLASS_UNIVERSAL", "PRIMITIVE_BIT", "TAG_SEQ", "TAG_INT", "ENCODED_TAG_SEQ", "ENCODED_TAG_INT", "base64Url", "base64", "signatureAsBuffer", "signature", "derToJose", "alg", "paramBytes", "maxEncodedParamLength", "inputLength", "offset", "seqLength", "rLength", "rOffset", "sLength", "sOffset", "rPadding", "sPadding", "dst", "o", "countPadding", "buf", "start", "stop", "padding", "needsSign", "joseToDer", "signatureBytes", "rsBytes", "shortLength", "require_util", "__commonJSMin", "exports", "snakeToCamel", "originalOrCamelOptions", "removeUndefinedValuesInObject", "isValidFile", "getWellKnownCertificateConfigFileLocation", "fs", "os", "path", "WELL_KNOWN_CERTIFICATE_CONFIG_FILE", "CLOUDSDK_CONFIG_DIRECTORY", "str", "match", "obj", "get", "key", "o", "LRUCache", "#cache", "options", "#moveToEnd", "value", "#evict", "item", "cutoffDate", "oldestItem", "object", "filePath", "configDir", "_isWindows", "require_package", "__commonJSMin", "exports", "module", "require_shared", "__commonJSMin", "exports", "pkg", "PRODUCT_NAME", "USER_AGENT", "require_authclient", "__commonJSMin", "exports", "events_1", "gaxios_1", "util_1", "google_logging_utils_1", "shared_cjs_1", "AuthClient", "_AuthClient", "opts", "options", "args", "input", "init", "url", "headers", "credentials", "target", "source", "xGoogUserProject", "authorizationHeader", "config", "nodeVersion", "userAgent", "symbols", "methodName", "logId", "logObject", "response", "error", "require_loginticket", "__commonJSMin", "exports", "LoginTicket", "env", "pay", "payload", "require_oauth2client", "__commonJSMin", "exports", "gaxios_1", "querystring", "stream", "formatEcdsa", "util_1", "crypto_1", "authclient_1", "loginticket_1", "CodeChallengeMethod", "CertificateFormat", "ClientAuthentication", "OAuth2Client", "_OAuth2Client", "options", "clientSecret", "redirectUri", "opts", "crypto", "codeVerifier", "codeChallenge", "codeOrOptions", "callback", "r", "e", "url", "headers", "values", "basic", "res", "tokens", "refreshToken", "p", "data", "refreshedAccessToken", "thisCreds", "err", "credentials", "token", "reAuthRetried", "statusCode", "mayRequireRefresh", "mayRequireRefreshWithNoRefreshToken", "isReadableStream", "isAuthErr", "response", "accessToken", "info", "nowTime", "format", "cacheControl", "cacheAge", "maxAge", "certificates", "key", "now", "jwt", "certs", "requiredAudience", "issuers", "maxExpiry", "segments", "signed", "signature", "envelope", "payload", "cert", "iat", "exp", "earliest", "latest", "aud", "audVerified", "accessTokenResponse", "expiryDate", "require_computeclient", "__commonJSMin", "exports", "gaxios_1", "gcpMetadata", "oauth2client_1", "Compute", "options", "tokenPath", "data", "instanceOptions", "e", "tokens", "targetAudience", "idTokenPath", "idToken", "res", "require_idtokenclient", "__commonJSMin", "exports", "oauth2client_1", "IdTokenClient", "options", "idToken", "payloadB64", "require_envDetect", "__commonJSMin", "exports", "clear", "getEnv", "gcpMetadata", "GCPEnv", "envPromise", "getEnvMemoized", "env", "isAppEngine", "isCloudFunction", "isComputeEngine", "isKubernetesEngine", "isCloudRun", "require_data_stream", "__commonJSMin", "exports", "module", "Buffer", "Stream", "util", "DataStream", "data", "require_buffer_equal_constant_time", "__commonJSMin", "exports", "module", "Buffer", "SlowBuffer", "bufferEq", "a", "b", "c", "i", "that", "origBufEqual", "origSlowBufEqual", "require_jwa", "__commonJSMin", "exports", "module", "Buffer", "crypto", "formatEcdsa", "util", "MSG_INVALID_ALGORITHM", "MSG_INVALID_SECRET", "MSG_INVALID_VERIFIER_KEY", "MSG_INVALID_SIGNER_KEY", "supportsKeyObjects", "checkIsPublicKey", "key", "typeError", "checkIsPrivateKey", "checkIsSecretKey", "fromBase64", "base64", "toBase64", "base64url", "padding", "i", "template", "args", "errMsg", "bufferOrString", "obj", "normalizeInput", "thing", "createHmacSigner", "bits", "secret", "hmac", "sig", "bufferEqual", "timingSafeEqual", "a", "b", "createHmacVerifier", "signature", "computedSig", "createKeySigner", "privateKey", "signer", "createKeyVerifier", "publicKey", "verifier", "createPSSKeySigner", "createPSSKeyVerifier", "createECDSASigner", "inner", "createECDSAVerifer", "result", "createNoneSigner", "createNoneVerifier", "algorithm", "signerFactories", "verifierFactories", "match", "algo", "require_tostring", "__commonJSMin", "exports", "module", "Buffer", "obj", "require_sign_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "base64url", "string", "encoding", "jwsSecuredInput", "header", "payload", "encodedHeader", "encodedPayload", "jwsSign", "opts", "secretOrKey", "algo", "securedInput", "signature", "SignStream", "secret", "secretStream", "e", "require_verify_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "JWS_REGEX", "isObject", "thing", "safeJsonParse", "headerFromJWS", "jwsSig", "encodedHeader", "securedInputFromJWS", "signatureFromJWS", "payloadFromJWS", "encoding", "payload", "isValidJws", "string", "jwsVerify", "algorithm", "secretOrKey", "err", "signature", "securedInput", "algo", "jwsDecode", "opts", "header", "VerifyStream", "secretStream", "valid", "obj", "e", "require_jws", "__commonJSMin", "exports", "SignStream", "VerifyStream", "ALGORITHMS", "opts", "require_src", "__commonJSMin", "exports", "fs", "_interopRequireWildcard", "_gaxios", "jws", "path", "_util", "e", "t", "r", "o", "i", "f", "_typeof", "_t3", "_classPrivateMethodInitSpec", "a", "_checkPrivateRedeclaration", "_classPrivateFieldInitSpec", "_classPrivateFieldSet", "s", "_assertClassBrand", "_classPrivateFieldGet", "n", "_defineProperties", "_toPropertyKey", "_createClass", "_classCallCheck", "_callSuper", "_getPrototypeOf", "_possibleConstructorReturn", "_isNativeReflectConstruct", "_assertThisInitialized", "_inherits", "_setPrototypeOf", "_wrapNativeSuper", "_isNativeFunction", "Wrapper", "_construct", "p", "_defineProperty", "_toPrimitive", "_regenerator", "c", "Generator", "u", "_regeneratorDefine2", "y", "G", "d", "l", "GeneratorFunction", "GeneratorFunctionPrototype", "asyncGeneratorStep", "_asyncToGenerator", "_next", "_throw", "readFile", "_callee", "_context", "ErrorWithCode", "GOOGLE_TOKEN_URL", "GOOGLE_REVOKE_TOKEN_URL", "_Error", "message", "code", "_this", "_inFlightRequest", "_GoogleToken_brand", "GoogleToken", "_options", "opts", "_configure", "now", "_this$eagerRefreshThr", "eagerRefreshThresholdMillis", "callback", "cb", "_getTokenAsync", "_getCredentials", "_callee2", "keyFile", "ext", "key", "body", "privateKey", "clientEmail", "_privateKey", "_t", "_context2", "getCredentials", "_x", "_revokeTokenAsync", "_x2", "_getTokenAsync2", "_callee3", "_context3", "_getTokenAsyncInner", "_x3", "_getTokenAsyncInner2", "_callee4", "creds", "_context4", "_ensureEmail", "_requestToken", "_revokeTokenAsync2", "_callee5", "url", "_context5", "options", "_requestToken2", "_callee6", "iat", "additionalClaims", "payload", "signedJWT", "_response", "_response2", "desc", "_t2", "_context6", "require_jwtaccess", "__commonJSMin", "exports", "jws", "util_1", "DEFAULT_HEADER", "JWTAccess", "_JWTAccess", "email", "key", "keyId", "eagerRefreshThresholdMillis", "url", "scopes", "cacheKey", "additionalClaims", "cachedToken", "now", "iat", "exp", "defaultClaims", "claim", "header", "payload", "signedJWT", "headers", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "require_jwtclient", "__commonJSMin", "exports", "gtoken_1", "jwtaccess_1", "oauth2client_1", "authclient_1", "JWT", "_JWT", "options", "scopes", "jwt", "url", "useSelfSignedJWT", "tokens", "useScopes", "headers", "targetAudience", "gtoken", "callback", "r", "result", "json", "inputStream", "resolve", "reject", "s", "chunk", "data", "e", "apiKey", "creds", "require_refreshclient", "__commonJSMin", "exports", "oauth2client_1", "authclient_1", "UserRefreshClient", "_UserRefreshClient", "optionsOrClientId", "clientSecret", "refreshToken", "eagerRefreshThresholdMillis", "forceRefreshOnFailure", "opts", "targetAudience", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "client", "require_impersonated", "__commonJSMin", "exports", "oauth2client_1", "gaxios_1", "util_1", "Impersonated", "_Impersonated", "options", "blobToSign", "name", "u", "body", "res", "tokenResponse", "error", "status", "message", "targetAudience", "require_oauth2common", "__commonJSMin", "exports", "getErrorFromOAuthErrorResponse", "gaxios_1", "crypto_1", "METHODS_SUPPORTING_REQUEST_BODY", "OAuthClientAuthHandler", "#crypto", "#clientAuthentication", "options", "opts", "bearerToken", "clientId", "clientSecret", "base64EncodedCreds", "method", "contentType", "data", "resp", "err", "errorCode", "errorDescription", "errorUri", "message", "newError", "keys", "key", "require_stscredentials", "__commonJSMin", "exports", "gaxios_1", "authclient_1", "oauth2common_1", "util_1", "StsCredentials", "_StsCredentials", "#tokenExchangeEndpoint", "options", "clientAuthentication", "stsCredentialsOptions", "headers", "values", "opts", "response", "stsSuccessfulResponse", "error", "require_baseexternalclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "util_1", "shared_cjs_1", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "DEFAULT_OAUTH_SCOPE", "DEFAULT_TOKEN_LIFESPAN", "WORKFORCE_AUDIENCE_PATTERN", "DEFAULT_TOKEN_URL", "BaseExternalAccountClient", "_BaseExternalAccountClient", "#pendingAccessToken", "options", "opts", "type", "clientId", "clientSecret", "subjectTokenType", "workforcePoolUserProject", "serviceAccountImpersonationUrl", "serviceAccountImpersonation", "serviceAccountImpersonationLifetime", "workforceAudiencePattern", "credentials", "accessTokenResponse", "headers", "callback", "r", "e", "projectNumber", "response", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "#internalRefreshAccessTokenAsync", "subjectToken", "stsCredentialsOptions", "additionalOptions", "additionalHeaders", "stsResponse", "audience", "match", "token", "successResponse", "accessToken", "now", "nodeVersion", "saImpersonation", "credentialSourceType", "require_filesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "readFile", "realpath", "lstat", "FileSubjectTokenSupplier", "opts", "parsedFilePath", "err", "subjectToken", "rawText", "require_urlsubjecttokensupplier", "__commonJSMin", "exports", "authclient_1", "UrlSubjectTokenSupplier", "opts", "context", "subjectToken", "require_certificatesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "crypto_1", "https", "CertificateSourceUnavailableError", "message", "InvalidConfigurationError", "CertificateSubjectTokenSupplier", "opts", "#resolveCertificateConfigFilePath", "certPath", "keyPath", "#getCertAndKeyPaths", "#getKeyAndCert", "#processChainFromPaths", "overridePath", "envPath", "wellKnownPath", "configPath", "fileContents", "config", "e", "cert", "key", "err", "leafCertBuffer", "leafCert", "chainCerts", "pem", "index", "leafIndex", "chainCert", "finalChain", "require_identitypoolclient", "__commonJSMin", "exports", "baseexternalclient_1", "util_1", "filesubjecttokensupplier_1", "urlsubjecttokensupplier_1", "certificatesubjecttokensupplier_1", "stscredentials_1", "gaxios_1", "IdentityPoolClient", "_IdentityPoolClient", "options", "opts", "credentialSource", "subjectTokenSupplier", "credentialSourceOpts", "formatOpts", "formatType", "formatSubjectTokenFieldName", "file", "url", "certificate", "headers", "certificateSubjecttokensupplier", "subjectToken", "mtlsAgent", "require_awsrequestsigner", "__commonJSMin", "exports", "gaxios_1", "crypto_1", "AWS_ALGORITHM", "AWS_REQUEST_TYPE", "AwsRequestSigner", "getCredentials", "region", "amzOptions", "requestPayloadData", "url", "method", "requestPayload", "additionalAmzHeaders", "awsSecurityCredentials", "uri", "headerMap", "generateAuthenticationHeaderMap", "headers", "awsSignedReq", "sign", "crypto", "key", "msg", "getSigningKey", "dateStamp", "serviceName", "kDate", "kRegion", "kService", "options", "now", "amzDate", "amzHeaders", "canonicalHeaders", "signedHeadersList", "signedHeaders", "payloadHash", "canonicalRequest", "credentialScope", "stringToSign", "signingKey", "signature", "authorizationHeader", "require_defaultawssecuritycredentialssupplier", "__commonJSMin", "exports", "authclient_1", "DefaultAwsSecurityCredentialsSupplier", "opts", "context", "#regionFromEnv", "metadataHeaders", "#getImdsV2SessionToken", "response", "#securityCredentialsFromEnv", "roleName", "#getAwsRoleName", "awsCreds", "#retrieveAwsSecurityCredentials", "transporter", "headers", "require_awsclient", "__commonJSMin", "exports", "awsrequestsigner_1", "baseexternalclient_1", "defaultawssecuritycredentialssupplier_1", "util_1", "gaxios_1", "AwsClient", "_AwsClient", "#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL", "options", "opts", "credentialSource", "awsSecurityCredentialsSupplier", "credentialSourceOpts", "regionUrl", "securityCredentialsUrl", "imdsV2SessionTokenUrl", "match", "reformattedHeader", "value", "key", "require_executable_response", "__commonJSMin", "exports", "SAML_SUBJECT_TOKEN_TYPE", "OIDC_SUBJECT_TOKEN_TYPE1", "OIDC_SUBJECT_TOKEN_TYPE2", "ExecutableResponse", "responseJson", "InvalidVersionFieldError", "InvalidSuccessFieldError", "InvalidTokenTypeFieldError", "InvalidSubjectTokenError", "InvalidCodeFieldError", "InvalidMessageFieldError", "ExecutableResponseError", "message", "InvalidExpirationTimeFieldError", "require_pluggable_auth_handler", "__commonJSMin", "exports", "executable_response_1", "childProcess", "fs", "ExecutableError", "message", "code", "PluggableAuthHandler", "_PluggableAuthHandler", "options", "envMap", "resolve", "reject", "child", "output", "data", "err", "timeout", "responseJson", "response", "error", "filePath", "responseString", "command", "components", "i", "require_pluggable_auth_client", "__commonJSMin", "exports", "baseexternalclient_1", "executable_response_1", "pluggable_auth_handler_1", "pluggable_auth_handler_2", "DEFAULT_EXECUTABLE_TIMEOUT_MILLIS", "MINIMUM_EXECUTABLE_TIMEOUT_MILLIS", "MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS", "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "MAXIMUM_EXECUTABLE_VERSION", "PluggableAuthClient", "options", "executableResponse", "envMap", "serviceAccountEmail", "require_externalclient", "__commonJSMin", "exports", "baseexternalclient_1", "identitypoolclient_1", "awsclient_1", "pluggable_auth_client_1", "ExternalAccountClient", "options", "require_externalAccountAuthorizedUserClient", "__commonJSMin", "exports", "authclient_1", "oauth2common_1", "gaxios_1", "stream", "baseexternalclient_1", "DEFAULT_TOKEN_URL", "ExternalAccountAuthorizedUserHandler", "_ExternalAccountAuthorizedUserHandler", "#tokenRefreshEndpoint", "options", "refreshToken", "headers", "opts", "response", "tokenRefreshResponse", "error", "ExternalAccountAuthorizedUserClient", "clientAuthentication", "accessTokenResponse", "callback", "r", "e", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "refreshResponse", "credentials", "now", "require_googleauth", "__commonJSMin", "exports", "child_process_1", "fs", "gaxios_1", "gcpMetadata", "os", "path", "crypto_1", "computeclient_1", "idtokenclient_1", "envDetect_1", "jwtclient_1", "refreshclient_1", "impersonated_1", "externalclient_1", "baseexternalclient_1", "authclient_1", "externalAccountAuthorizedUserClient_1", "util_1", "GoogleAuth", "#pendingAuthClient", "opts", "client", "callback", "r", "projectId", "universeDomain", "e", "optionsOrCallback", "options", "#prepareAndCacheClient", "credential", "quotaProjectIdOverride", "credentialsPath", "location", "home", "filePath", "err", "readStream", "json", "sourceClient", "targetPrincipal", "targetScopes", "preferredUniverseDomain", "inputStream", "resolve", "reject", "chunks", "chunk", "data", "apiKey", "sys", "stdout", "creds", "serviceAccountEmail", "client_email", "universe_domain", "#determineClient", "stream", "targetAudience", "url", "headers", "args", "endpoint", "universe", "crypto", "emailOrUniqueId", "require_iam", "__commonJSMin", "exports", "IAMAuth", "selector", "token", "require_downscopedclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "STS_SUBJECT_TOKEN_TYPE", "DownscopedClient", "options", "credentialAccessBoundary", "rule", "credentials", "accessTokenResponse", "headers", "opts", "callback", "r", "e", "reAuthRetried", "response", "requestHeaders", "res", "statusCode", "isReadableStream", "subjectToken", "stsCredentialsOptions", "stsResponse", "sourceCredExpireDate", "expiryDate", "downscopedAccessToken", "now", "require_passthrough", "__commonJSMin", "exports", "authclient_1", "PassThroughClient", "opts", "require_src", "__commonJSMin", "exports", "googleauth_1", "authclient_1", "computeclient_1", "envDetect_1", "iam_1", "idtokenclient_1", "jwtaccess_1", "jwtclient_1", "impersonated_1", "oauth2client_1", "loginticket_1", "refreshclient_1", "awsclient_1", "awsrequestsigner_1", "identitypoolclient_1", "externalclient_1", "baseexternalclient_1", "downscopedclient_1", "pluggable_auth_client_1", "passthrough_1", "auth", "Fastify", "cors", "import_json5", "readFileSync", "existsSync", "join", "config", "ConfigService", "options", "jsonPath", "jsonContent", "jsonConfig", "JSON5", "error", "envPath", "result", "envConfig", "env", "parsed", "path", "key", "defaultValue", "value", "summary", "createApiError", "message", "statusCode", "code", "type", "error", "errorHandler", "request", "reply", "response", "ProxyAgent", "sendUnifiedRequest", "url", "request", "config", "logger", "headers", "key", "value", "combinedSignal", "timeoutSignal", "controller", "abortHandler", "fetchOptions", "version", "handleTransformerEndpoint", "req", "reply", "fastify", "transformer", "body", "providerName", "provider", "createApiError", "requestBody", "config", "bypass", "processRequestTransformers", "response", "sendRequestToProvider", "finalResponse", "processResponseTransformers", "formatResponse", "headers", "shouldBypassTransformers", "transformOut", "providerTransformer", "transformIn", "modelTransformer", "url", "auth", "sendUnifiedRequest", "errorText", "registerApiRoutes", "version", "transformersWithEndpoint", "request", "name", "baseUrl", "apiKey", "models", "isValidUrl", "LLMService", "providerService", "request", "id", "updates", "enabled", "modelName", "route", "provider", "model", "ProviderService", "configService", "transformerService", "logger", "providersConfig", "providerConfig", "transformer", "key", "Constructor", "transformerInstance", "error", "request", "provider", "model", "fullModel", "route", "name", "id", "updates", "updatedProvider", "enabled", "modelName", "modelNames", "transformerConfig", "acc", "item", "config", "models", "byteToHex", "i", "unsafeStringify", "arr", "offset", "randomFillSync", "rnds8Pool", "poolPtr", "rng", "randomUUID", "native_default", "v4", "options", "buf", "offset", "native_default", "rnds", "rng", "i", "unsafeStringify", "v4_default", "getThinkLevel", "thinking_budget", "AnthropicTransformer", "request", "provider", "messages", "textParts", "item", "msg", "index", "toolParts", "c", "tool", "toolIndex", "toolMessage", "textAndMediaParts", "part", "assistantMessage", "text", "toolCallParts", "result", "getThinkLevel", "response", "context", "convertedStream", "data", "anthropicResponse", "tools", "openaiStream", "controller", "encoder", "messageId", "stopReasonMessageDelta", "model", "hasStarted", "hasTextContentStarted", "hasFinished", "toolCalls", "toolCallIndexToContentBlockIndex", "totalChunks", "contentChunks", "toolCallChunks", "isClosed", "isThinkingStarted", "contentIndex", "currentContentBlockIndex", "safeEnqueue", "dataStr", "error", "safeClose", "contentBlockStop", "messageStop", "reader", "decoder", "buffer", "done", "value", "lines", "line", "chunk", "errorMessage", "messageStart", "choice", "contentBlockStart", "thinkingSignature", "thinkingChunk", "anthropicChunk", "annotation", "v4_default", "processedInThisChunk", "toolCall", "toolCallIndex", "newContentBlockIndex", "toolCallId", "toolCallName", "toolCallInfo", "existingToolCall", "blockIndex", "currentToolCall", "fixedArgument", "fixedChunk", "fixError", "parseError", "controllerError", "releaseError", "reason", "openaiResponse", "content", "id", "parsedInput", "argumentsStr", "createApiError", "Type", "flattenTypeArrayToAnyOf", "typeList", "resultingSchema", "listWithoutNull", "type", "upperCaseType", "i", "processJsonSchema", "_jsonSchema", "genAISchema", "schemaFieldNames", "listSchemaFieldNames", "dictSchemaFieldNames", "incomingAnyOf", "fieldName", "fieldValue", "upperCaseValue", "listSchemaFieldValue", "item", "dictSchemaFieldValue", "key", "value", "tTool", "tool", "functionDeclaration", "buildRequestBody", "request", "tools", "functionDeclarations", "body", "message", "role", "parts", "content", "toolCall", "toolConfig", "transformRequestOut", "contents", "model", "max_tokens", "temperature", "stream", "tool_choice", "unifiedChatRequest", "part", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "candidate", "groundingChunk", "index", "support", "error", "reader", "buffer", "done", "lines", "GeminiTransformer", "request", "provider", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "getAccessToken", "GoogleAuth", "error", "VertexGeminiTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "DeepseekTransformer", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "TooluseTransformer", "request", "response", "jsonResponse", "toolCall", "toolArguments", "decoder", "encoder", "exitToolIndex", "exitToolResponse", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "setExitToolIndex", "appendExitToolResponse", "data", "modifiedLine", "done", "value", "chunk", "val", "content", "error", "e", "OpenrouterTransformer", "options", "request", "msg", "item", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "thinkingChunk", "thinkingLine", "signature", "tool", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "MaxTokenTransformer", "options", "request", "GroqTransformer", "request", "msg", "item", "tool", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "CleancacheTransformer", "request", "msg", "item", "import_json5", "JSONRepairError", "Error", "constructor", "message", "position", "isHex", "char", "test", "isDigit", "isValidStringCharacter", "isDelimiter", "includes", "isFunctionNameCharStart", "isFunctionNameChar", "regexUrlStart", "regexUrlChar", "isUnquotedStringDelimiter", "isStartOfValue", "isQuote", "regexStartOfValue", "isControlCharacter", "isWhitespace", "text", "index", "code", "charCodeAt", "codeSpace", "codeNewline", "codeTab", "codeReturn", "isWhitespaceExceptNewline", "isSpecialWhitespace", "codeNonBreakingSpace", "codeEnQuad", "codeHairSpace", "codeNarrowNoBreakSpace", "codeMediumMathematicalSpace", "codeIdeographicSpace", "isDoubleQuoteLike", "isSingleQuoteLike", "isDoubleQuote", "isSingleQuote", "stripLastOccurrence", "textToStrip", "stripRemainingText", "arguments", "length", "undefined", "lastIndexOf", "substring", "insertBeforeLastWhitespace", "textToInsert", "removeAtIndex", "start", "count", "endsWithCommaOrNewline", "controlCharacters", "escapeCharacters", "b", "f", "n", "r", "t", "jsonrepair", "text", "i", "output", "parseMarkdownCodeBlock", "parseValue", "throwUnexpectedEnd", "processedComma", "parseCharacter", "parseWhitespaceAndSkipComments", "isStartOfValue", "endsWithCommaOrNewline", "insertBeforeLastWhitespace", "parseNewlineDelimitedJSON", "stripLastOccurrence", "length", "throwUnexpectedCharacter", "processed", "parseObject", "parseArray", "parseString", "parseNumber", "parseKeywords", "parseUnquotedString", "parseRegex", "skipNewline", "arguments", "undefined", "start", "changed", "parseWhitespace", "parseComment", "_isWhiteSpace", "isWhitespace", "isWhitespaceExceptNewline", "whitespace", "isSpecialWhitespace", "atEndOfBlockComment", "blocks", "skipMarkdownCodeBlock", "isFunctionNameCharStart", "isFunctionNameChar", "block", "end", "slice", "char", "skipCharacter", "skipEscapeCharacter", "skipEllipsis", "initial", "throwObjectKeyExpected", "processedColon", "truncatedText", "throwColonExpected", "processedValue", "stopAtDelimiter", "stopAtIndex", "skipEscapeChars", "isQuote", "isEndQuote", "isDoubleQuote", "isSingleQuote", "isSingleQuoteLike", "isDoubleQuoteLike", "iBefore", "oBefore", "str", "iPrev", "prevNonWhitespaceIndex", "isDelimiter", "charAt", "substring", "iQuote", "oQuote", "isDigit", "parseConcatenatedString", "iPrevChar", "prevChar", "isUnquotedStringDelimiter", "regexUrlStart", "test", "regexUrlChar", "j", "isHex", "throwInvalidUnicodeCharacter", "isControlCharacter", "isValidStringCharacter", "throwInvalidCharacter", "removeAtIndex", "atEndOfNumber", "repairNumberEndingWithNumericSymbol", "num", "hasInvalidLeadingZero", "parseKeyword", "name", "value", "isKey", "symbol", "JSON", "stringify", "prev", "JSONRepairError", "chars", "parseToolArguments", "argsString", "logger", "jsonError", "args", "JSON5", "json5Error", "repairedJson", "jsonrepair", "repairError", "EnhanceToolTransformer", "response", "jsonResponse", "toolCall", "parseToolArguments", "decoder", "encoder", "currentToolCall", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processCompletedToolCall", "data", "finalArgs", "e", "delta", "modifiedData", "modifiedLine", "processLine", "context", "jsonStr", "toolCallDelta", "done", "value", "chunk", "decodeError", "val", "content", "error", "ReasoningTransformer", "options", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "SamplingTransformer", "options", "request", "MaxCompletionTokens", "request", "buildRequestBody", "request", "messages", "i", "message", "isLastMessage", "isAssistantMessage", "content", "item", "requestBody", "tool", "transformRequestOut", "vertexRequest", "result", "msg", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "error", "stream", "reader", "buffer", "done", "value", "lines", "getAccessToken", "GoogleAuth", "error", "VertexClaudeTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "convertContentToString", "content", "item", "CerebrasTransformer", "request", "provider", "transformedRequest", "systemContent", "message", "transformedMessage", "response", "StreamOptionsTransformer", "request", "transformer_default", "AnthropicTransformer", "GeminiTransformer", "VertexGeminiTransformer", "VertexClaudeTransformer", "DeepseekTransformer", "TooluseTransformer", "OpenrouterTransformer", "MaxTokenTransformer", "GroqTransformer", "CleancacheTransformer", "EnhanceToolTransformer", "ReasoningTransformer", "SamplingTransformer", "MaxCompletionTokens", "CerebrasTransformer", "StreamOptionsTransformer", "TransformerService", "configService", "logger", "name", "transformer", "result", "config", "module", "__require", "instance", "error", "transformer_default", "TransformerStatic", "transformerInstance", "transformers", "createApp", "logger", "fastify", "Fastify", "errorHandler", "cors", "Server", "options", "ConfigService", "TransformerService", "ProviderService", "LLMService", "plugin", "hookName", "hookFunction", "request", "reply", "done", "req", "body", "provider", "model", "err", "registerApiRoutes", "address", "shutdown", "signal", "error", "server_default"] +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7efae79baa4d2dcc75a8b2adccfa61903655fccc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/worker.js"], + "sourcesContent": ["/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\nconst { workerData, parentPort } = require('worker_threads')\nconst { WRITE_INDEX, READ_INDEX } = require('./indexes')\nconst { waitDiff } = require('./wait')\n\nconst {\n dataBuf,\n filename,\n stateBuf\n} = workerData\n\nlet destination\n\nconst state = new Int32Array(stateBuf)\nconst data = Buffer.from(dataBuf)\n\nasync function start () {\n let worker\n try {\n if (filename.endsWith('.ts') || filename.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (!process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n // Remove extra forwardslash on Windows\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } else {\n worker = (await realImport(filename))\n }\n } catch (error) {\n // A yarn user that tries to start a ThreadStream for an external module\n // provides a filename pointing to a zip file.\n // eg. require.resolve('pino-elasticsearch') // returns /foo/pino-elasticsearch-npm-6.1.0-0c03079478-6915435172.zip/bar.js\n // The `import` will fail to try to load it.\n // This catch block executes the `require` fallback to load the module correctly.\n // In fact, yarn modifies the `require` function to manage the zipped path.\n // More details at https://github.com/pinojs/pino/pull/1113\n // The error codes may change based on the node.js version (ENOTDIR > 12, ERR_MODULE_NOT_FOUND <= 12 )\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND') &&\n filename.startsWith('file://')) {\n worker = realRequire(decodeURIComponent(filename.replace('file://', '')))\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof worker === 'object') worker = worker.default\n if (typeof worker === 'object') worker = worker.default\n\n destination = await worker(workerData.workerData)\n\n destination.on('error', function (err) {\n Atomics.store(state, WRITE_INDEX, -2)\n Atomics.notify(state, WRITE_INDEX)\n\n Atomics.store(state, READ_INDEX, -2)\n Atomics.notify(state, READ_INDEX)\n\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n })\n\n destination.on('close', function () {\n // process._rawDebug('worker close emitted')\n const end = Atomics.load(state, WRITE_INDEX)\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(() => {\n process.exit(0)\n })\n })\n}\n\n// No .catch() handler,\n// in case there is an error it goes\n// to unhandledRejection\nstart().then(function () {\n parentPort.postMessage({\n code: 'READY'\n })\n\n process.nextTick(run)\n})\n\nfunction run () {\n const current = Atomics.load(state, READ_INDEX)\n const end = Atomics.load(state, WRITE_INDEX)\n\n // process._rawDebug(`pre state ${current} ${end}`)\n\n if (end === current) {\n if (end === data.length) {\n waitDiff(state, READ_INDEX, end, Infinity, run)\n } else {\n waitDiff(state, WRITE_INDEX, end, Infinity, run)\n }\n return\n }\n\n // process._rawDebug(`post state ${current} ${end}`)\n\n if (end === -1) {\n // process._rawDebug('end')\n destination.end()\n return\n }\n\n const toWrite = data.toString('utf8', current, end)\n // process._rawDebug('worker writing: ' + toWrite)\n\n const res = destination.write(toWrite)\n\n if (res) {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(run)\n } else {\n destination.once('drain', function () {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n run()\n })\n }\n}\n\nprocess.on('unhandledRejection', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.on('uncaughtException', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.once('exit', exitCode => {\n if (exitCode !== 0) {\n process.exit(exitCode)\n return\n }\n if (destination?.writableNeedDrain && !destination?.writableEnded) {\n parentPort.postMessage({\n code: 'WARNING',\n err: new Error('ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream')\n })\n }\n\n process.exit(0)\n})\n"], + "mappings": "uTAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,CAGA,IAAMC,EAAa,IAA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GAAG,qBAAsB,SAAUF,EAAK,CAC9Cb,EAAW,YAAY,CACrB,KAAM,QACN,IAAAa,CACF,CAAC,EACD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,GAAG,oBAAqB,SAAUA,EAAK,CAC7Cb,EAAW,YAAY,CACrB,KAAM,QACN,IAAAa,CACF,CAAC,EACD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,KAAK,OAAQK,GAAY,CAC/B,GAAIA,IAAa,EAAG,CAClB,QAAQ,KAAKA,CAAQ,EACrB,MACF,CACIX,GAAa,mBAAqB,CAACA,GAAa,eAClDP,EAAW,YAAY,CACrB,KAAM,UACN,IAAK,IAAI,MAAM,4JAA4J,CAC7K,CAAC,EAGH,QAAQ,KAAK,CAAC,CAChB,CAAC", + "names": ["require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "__require", "require_indexes", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "realImport", "realRequire", "workerData", "parentPort", "WRITE_INDEX", "READ_INDEX", "waitDiff", "dataBuf", "filename", "stateBuf", "destination", "state", "data", "start", "worker", "error", "err", "end", "run", "current", "toWrite", "exitCode"] +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..827f1db09aac5d9f6b2e63d56a509ae67faaf0e6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts @@ -0,0 +1,20 @@ +import type * as fsStat from '@nodelib/fs.stat'; +import type { Dirent, ErrnoException } from '../types'; +export interface ReaddirAsynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }, callback: (error: ErrnoException | null, files: Dirent[]) => void): void; + (filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void; +} +export interface ReaddirSynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }): Dirent[]; + (filepath: string): string[]; +} +export declare type FileSystemAdapter = fsStat.FileSystemAdapter & { + readdir: ReaddirAsynchronousMethod; + readdirSync: ReaddirSynchronousMethod; +}; +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js new file mode 100644 index 0000000000000000000000000000000000000000..99c70d3d635f73d2704b02695933770401b14d37 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.scandirSync = exports.scandir = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..e8e2f0a9cba94ed06b7762f2846ab88330aaa44e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const rpl = require("run-parallel"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir(directory, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b4d08b57a0de23a030b494abbb236239638b122 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts @@ -0,0 +1 @@ +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js new file mode 100644 index 0000000000000000000000000000000000000000..8724cb59afe97cdfebdf6b50bdf36534537e781c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = void 0; +function joinPathSegments(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e05c8f072cb5766844c31f6d8424c692f0caacac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts @@ -0,0 +1,5 @@ +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare function read(directory: string, settings: Settings): Entry[]; +export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[]; +export declare function readdir(directory: string, settings: Settings): Entry[]; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..146db3434f42252e4071db1624074a666fe21b4a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +exports.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..ace7c74d63f6da763b2711a4119d6005f5c3b187 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b41954e79d847e0f085ce4235b8ee62fddb1977 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts @@ -0,0 +1,2 @@ +import * as fs from './fs'; +export { fs }; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc08c8ca1f1c72aa9622352ca5d55f65198767d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..1521c3616eaee4439c5cd1a855c97d029d4dab38 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4b3d444302ff6b5715a79341156f61350bd0a1b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts @@ -0,0 +1,16 @@ +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLink?: boolean; + fs?: Partial; + markSymbolicLink?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLink: boolean; + readonly fs: fs.FileSystemAdapter; + readonly markSymbolicLink: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + constructor(_options?: Options); + private _getValue; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4c2529ce8a385a0215ddf188b8a46163b2e18842 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0; +const async_1 = require("./async"); +exports.AsyncProvider = async_1.default; +const stream_1 = require("./stream"); +exports.StreamProvider = stream_1.default; +const sync_1 = require("./sync"); +exports.SyncProvider = sync_1.default; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..51298b0f58f14b0c9b9f36061cdd0c0b950ba2f3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const async_1 = require("../readers/async"); +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..ebe8dd5735858b58c0d6a38cdb925c85c7c03651 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const fsScandir = require("@nodelib/fs.scandir"); +const fastq = require("fastq"); +const common = require("./common"); +const reader_1 = require("./reader"); +class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af410335363f14e3d0bdd44054917e08c6ba57ad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts @@ -0,0 +1,15 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry } from '../types'; +import Reader from './reader'; +export default class SyncReader extends Reader { + protected readonly _scandir: typeof fsScandir.scandirSync; + private readonly _storage; + private readonly _queue; + read(): Entry[]; + private _pushToQueue; + private _handleQueue; + private _handleDirectory; + private _handleError; + private _handleEntry; + private _pushToStorage; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1c4b45f6b52bd167482312568a4ba7f4b9bba74 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts @@ -0,0 +1,30 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry, Errno } from './types'; +export declare type FilterFunction = (value: T) => boolean; +export declare type DeepFilterFunction = FilterFunction; +export declare type EntryFilterFunction = FilterFunction; +export declare type ErrorFilterFunction = FilterFunction; +export interface Options { + basePath?: string; + concurrency?: number; + deepFilter?: DeepFilterFunction; + entryFilter?: EntryFilterFunction; + errorFilter?: ErrorFilterFunction; + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly basePath?: string; + readonly concurrency: number; + readonly deepFilter: DeepFilterFunction | null; + readonly entryFilter: EntryFilterFunction | null; + readonly errorFilter: ErrorFilterFunction | null; + readonly pathSegmentSeparator: string; + readonly fsScandirSettings: fsScandir.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..d7a85c81eeecf8fd230e6fecedc9550bddb2ff93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsScandir = require("@nodelib/fs.scandir"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/LICENSE b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/README.md b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c799624668f9f1d22f685a8ac8113b090bbb7b4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Fri, 15 Aug 2025 08:39:32 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b79fc2197d3c2fdc473d7e0eab2e189b773b1133 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1056 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls(fn: undefined, exact?: number): () => void; + calls any>(fn: Func, exact?: number): Func; + calls any>(fn?: Func, exact?: number): Func | (() => void); + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + | "AssertionError" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + AssertionError: typeof AssertionError; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert/strict.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f333913a4565f7067b05ddbc415490e585f2d1e1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/async_hooks.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2377689f865bf238b24201284c843f21ccc321cf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,623 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/buffer.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbdf207cd1234609fdfaa1715a00d1d27e415d1b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1930 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * 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' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * 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='utf8'] 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; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/child_process.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a12a8c82ded1fd486d3ef901e398a456aff33f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1453 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js) + */ +declare module "child_process" { + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v24.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..156e7856360bf532de1d82080e425573e9b2d749 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/console.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c923bd0acbc43d7e8b7fa656dd8e0b8b98d4123d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/crypto.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3c7d67174f00eac30e4b82994534ba25f7e7003 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4532 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v24.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` + * (for Diffie-Hellman), `'ec'`, `'x448'`, or `'x25519'` (for ECDH). + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: Buffer) => void, + ): void; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v24.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/dgram.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35239f92cc6a49247b5415c0f5473b68f569ee5f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,599 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa5ed691b04d838aa063d42d5e72cb77dc762214 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,578 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f3bd7ad42f5bf51a7f766b1c6940bd56cb3a123 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4440 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | undefined | null; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadSyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs/promises.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3386aa494cf4186a5e88577f5430604aeffefa2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1277 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: FileReadOptions, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/http.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4df8fad912fdae09a8628792d79d83cb0c45a69b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/http.d.ts @@ -0,0 +1,2046 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v24.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). + * @since v22.5.0 + */ + const WebSocket: import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b005c11450f068b131b79ca972b17e5fb44dc57 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/index.d.ts @@ -0,0 +1,94 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/inspector.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06333e4956c4c110c66152da0479b2f4e8ae1550 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,4211 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable', callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable', callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: 'Network.getRequestPostData', callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: 'Network.getResponseBody', callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: 'Network.streamResourceContent', + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: 'Network.streamResourceContent', callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + class Session extends EventEmitter { + /** + * Create a new instance of the `inspector.Session` class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable'): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable'): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: 'Network.streamResourceContent', params?: Network.StreamResourceContentParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/perf_hooks.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51d78d0b1230d4d7936eda198c46f1a36d21c833 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,984 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/process.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7428b36a4fa520fdedcb6dabb2a1a1482908974d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/process.d.ts @@ -0,0 +1,2073 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v24.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v24.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v24.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v24.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/querystring.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aaeefe8d3d38c80055964d56a9a3d5fc27e64c22 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/readline/promises.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0ebf4ba58ff122abdac2447259ccc0d0afcb59f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sea.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5119ede087d0b60b0733438fa885e906534b4169 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sqlite.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9019832f5866f6745bf784dacf1dfbfb360c3794 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,687 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | Uint8Array; + /** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */ + type SupportedValueType = SQLOutputValue; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): Uint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): Uint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * Callback function that will be called with the number of pages copied and the total number of + * pages. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that resolves when the backup is completed and rejects if an error occurs. + */ + function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/consumers.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..746d6e508266ac6fa68ee26d852d8d63ab3a15ca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/promises.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d54c14c60fa3590259439e2d02b995710966a664 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/web.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..881e29c089fdb1819971fa2eba808344268b94a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,622 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/string_decoder.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3632c163006ba2e31880cfcf61f4e9944265d309 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/test.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d397dbaabf074affaedd63b26c0259dcfd482dd3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/test.d.ts @@ -0,0 +1,2334 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v24.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: "test:watch:restarted", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: "test:watch:restarted"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: "test:watch:restarted", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: "test:watch:restarted", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: "test:watch:restarted", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: "test:watch:restarted", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends + Pick< + typeof import("assert"), + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws" + > + { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/timers.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30a91c0644e9b8992ba8aaa16efd24d8ef61668b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/timers.d.ts @@ -0,0 +1,285 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/tls.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9c4f244bf4f5a1d5585c992dc6da28d3a66aebd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1213 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d19026dc2ff99c5a865defba1953ec7588278345 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,460 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @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. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): 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(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): 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=0] The starting offset within `view`. + * @param [length=view.length - offset] 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=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] 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; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + type NonSharedBuffer = Buffer; + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..255e204813d2bb15c6849889b0de395f8ef5a83b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,20 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b98cc67db600b43e0e21b4e1dda713be9aa3a282 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,96 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9793c72ea8a0ae51e9b5839ab11c4575a70c7a9a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,96 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/url.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..83e3872e4837109fee29eb4030a2084814ffde9d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/url.d.ts @@ -0,0 +1,1025 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): Buffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. + * Returns `null` if `input` is not a valid. + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + * @since v22.1.0 + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + /** + * @since v23.8.0 + * @experimental + */ + class URLPattern { + constructor(input: string | URLPatternInit, baseURL: string, options?: URLPatternOptions); + constructor(input?: string | URLPatternInit, options?: URLPatternOptions); + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + readonly username: string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { + URL as _URL, + URLPattern as _URLPattern, + URLPatternInit as _URLPatternInit, + URLPatternResult as _URLPatternResult, + URLSearchParams as _URLSearchParams, + } from "url"; + global { + interface URL extends _URL {} + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + interface URLSearchParams extends _URLSearchParams {} + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + interface URLPatternInit extends _URLPatternInit {} + interface URLPatternResult extends _URLPatternResult {} + interface URLPattern extends _URLPattern {} + var URLPattern: typeof _URLPattern; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/v8.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d9af4e2b7cb90c7e0cc4f70a841a608366f6eb9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/v8.d.ts @@ -0,0 +1,919 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/vm.d.ts b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bba2e0ba49cc7c8f17bf6a4ef692dacc4fe5ff9d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/india-h200-1-workspace/claude-code-router/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1036 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: "source" | "evaluation", + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader