WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,402 @@
declare var ajv: {
(options?: ajv.Options): ajv.Ajv;
new(options?: ajv.Options): ajv.Ajv;
ValidationError: typeof AjvErrors.ValidationError;
MissingRefError: typeof AjvErrors.MissingRefError;
$dataMetaSchema: object;
}
declare namespace AjvErrors {
class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
}
declare namespace ajv {
type ValidationError = AjvErrors.ValidationError;
type MissingRefError = AjvErrors.MissingRefError;
interface Ajv {
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default).
* @param {string|object|Boolean} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>;
/**
* Create validating function for passed schema.
* @param {object|Boolean} schema schema object
* @return {Function} validating function
*/
compile(schema: object | boolean): ValidateFunction;
/**
* Creates validating function for passed schema with asynchronous loading of missing schemas.
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
* @this Ajv
* @param {object|Boolean} schema schema object
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function.
* @return {PromiseLike<ValidateFunction>} validating function
*/
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>;
/**
* Adds schema to the instance.
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @return {Ajv} this for method chaining
*/
addSchema(schema: Array<object> | object, key?: string): Ajv;
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @param {object} schema schema object
* @param {string} key optional schema key
* @return {Ajv} this for method chaining
*/
addMetaSchema(schema: object, key?: string): Ajv;
/**
* Validate schema
* @param {object|Boolean} schema schema to validate
* @return {Boolean} true if schema is valid
*/
validateSchema(schema: object | boolean): boolean;
/**
* Get compiled schema from the instance by `key` or `ref`.
* @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema.
*/
getSchema(keyRef: string): ValidateFunction | undefined;
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv;
/**
* Add custom format
* @param {string} name format name
* @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv;
/**
* Define custom keyword
* @this Ajv
* @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords.
* @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
* @return {Ajv} this for method chaining
*/
addKeyword(keyword: string, definition: KeywordDefinition): Ajv;
/**
* Get keyword definition
* @this Ajv
* @param {string} keyword pre-defined or custom keyword.
* @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
*/
getKeyword(keyword: string): object | boolean;
/**
* Remove keyword
* @this Ajv
* @param {string} keyword pre-defined or custom keyword.
* @return {Ajv} this for method chaining
*/
removeKeyword(keyword: string): Ajv;
/**
* Validate keyword
* @this Ajv
* @param {object} definition keyword definition object
* @param {boolean} throwError true to throw exception if definition is invalid
* @return {boolean} validation result
*/
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean;
/**
* Convert array of error message objects to string
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {object} options optional options with properties `separator` and `dataVar`.
* @return {string} human readable string with all errors descriptions
*/
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject> | null;
_opts: Options;
}
interface CustomLogger {
log(...args: any[]): any;
warn(...args: any[]): any;
error(...args: any[]): any;
}
interface ValidateFunction {
(
data: any,
dataPath?: string,
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | PromiseLike<any>;
schema?: object | boolean;
errors?: null | Array<ErrorObject>;
refs?: object;
refVal?: Array<any>;
root?: ValidateFunction | object;
$async?: true;
source?: object;
}
interface Options {
$data?: boolean;
allErrors?: boolean;
verbose?: boolean;
jsonPointers?: boolean;
uniqueItems?: boolean;
unicode?: boolean;
format?: false | string;
formats?: object;
keywords?: object;
unknownFormats?: true | string[] | 'ignore';
schemas?: Array<object> | object;
schemaId?: '$id' | 'id' | 'auto';
missingRefs?: true | 'ignore' | 'fail';
extendRefs?: true | 'ignore' | 'fail';
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>;
removeAdditional?: boolean | 'all' | 'failing';
useDefaults?: boolean | 'empty' | 'shared';
coerceTypes?: boolean | 'array';
strictDefaults?: boolean | 'log';
strictKeywords?: boolean | 'log';
strictNumbers?: boolean;
async?: boolean | string;
transpile?: string | ((code: string) => string);
meta?: boolean | object;
validateSchema?: boolean | 'log';
addUsedSchema?: boolean;
inlineRefs?: boolean | number;
passContext?: boolean;
loopRequired?: number;
ownProperties?: boolean;
multipleOfPrecision?: boolean | number;
errorDataPath?: string,
messages?: boolean;
sourceCode?: boolean;
processCode?: (code: string, schema: object) => string;
cache?: object;
logger?: CustomLogger | false;
nullable?: boolean;
serialize?: ((schema: object | boolean) => any) | false;
regExp?: (pattern: string) => RegExpLike;
}
interface RegExpLike {
test: (s: string) => boolean;
}
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>);
interface NumberFormatDefinition {
type: "number",
validate: NumberFormatValidator;
compare?: (data1: number, data2: number) => number;
async?: boolean;
}
interface StringFormatDefinition {
type?: "string",
validate: FormatValidator;
compare?: (data1: string, data2: string) => number;
async?: boolean;
}
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
interface KeywordDefinition {
type?: string | Array<string>;
async?: boolean;
$data?: boolean;
errors?: boolean | string;
metaSchema?: object;
// schema: false makes validate not to expect schema (ValidateFunction)
schema?: boolean;
statements?: boolean;
dependencies?: Array<string>;
modifying?: boolean;
valid?: boolean;
// one and only one of the following properties should be present
validate?: SchemaValidateFunction | ValidateFunction;
compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction;
macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean;
inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string;
}
interface CompilationContext {
level: number;
dataLevel: number;
dataPathArr: string[];
schema: any;
schemaPath: string;
baseId: string;
async: boolean;
opts: Options;
formats: {
[index: string]: FormatDefinition | undefined;
};
keywords: {
[index: string]: KeywordDefinition | undefined;
};
compositeRule: boolean;
validate: (schema: object) => boolean;
util: {
copy(obj: any, target?: any): any;
toHash(source: string[]): { [index: string]: true | undefined };
equal(obj: any, target: any): boolean;
getProperty(str: string): string;
schemaHasRules(schema: object, rules: any): string;
escapeQuotes(str: string): string;
toQuotedString(str: string): string;
getData(jsonPointer: string, dataLevel: number, paths: string[]): string;
escapeJsonPointer(str: string): string;
unescapeJsonPointer(str: string): string;
escapeFragment(str: string): string;
unescapeFragment(str: string): string;
};
self: Ajv;
}
interface SchemaValidateFunction {
(
schema: any,
data: any,
parentSchema?: object,
dataPath?: string,
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | PromiseLike<any>;
errors?: Array<ErrorObject>;
}
interface ErrorsTextOptions {
separator?: string;
dataVar?: string;
}
interface ErrorObject {
keyword: string;
dataPath: string;
schemaPath: string;
params: ErrorParameters;
// Added to validation errors of propertyNames keyword schema
propertyName?: string;
// Excluded if messages set to false.
message?: string;
// These are added with the `verbose` option.
schema?: any;
parentSchema?: object;
data?: any;
}
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams |
PatternRequiredParams | PropertyNamesParams |
IfParams | SwitchParams | NoParams | EnumParams;
interface RefParams {
ref: string;
}
interface LimitParams {
limit: number;
}
interface AdditionalPropertiesParams {
additionalProperty: string;
}
interface DependenciesParams {
property: string;
missingProperty: string;
depsCount: number;
deps: string;
}
interface FormatParams {
format: string
}
interface ComparisonParams {
comparison: string;
limit: number | string;
exclusive: boolean;
}
interface MultipleOfParams {
multipleOf: number;
}
interface PatternParams {
pattern: string;
}
interface RequiredParams {
missingProperty: string;
}
interface TypeParams {
type: string;
}
interface UniqueItemsParams {
i: number;
j: number;
}
interface CustomParams {
keyword: string;
}
interface PatternRequiredParams {
missingPattern: string;
}
interface PropertyNamesParams {
propertyName: string;
}
interface IfParams {
failingKeyword: string;
}
interface SwitchParams {
caseIndex: number;
}
interface NoParams { }
interface EnumParams {
allowedValues: Array<any>;
}
}
export = ajv;

View File

@@ -0,0 +1,172 @@
"use strict";
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.sha256_base64url = exports.sha256_base64 = exports.sha256_hex = exports.sha1_base64url = exports.sha1_base64 = exports.sha1_hex = exports.md5_base64url = exports.md5_base64 = exports.md5_hex = exports.hex = exports.uppercase = exports.lowercase = exports.undefined = exports.null = exports.boolean = exports.number = exports.integer = exports.bigint = exports.string = exports.date = exports.e164 = exports.httpProtocol = exports.domain = exports.hostname = exports.base64url = exports.base64 = exports.cidrv6 = exports.cidrv4 = exports.mac = exports.ipv6 = exports.ipv4 = exports.browserEmail = exports.idnEmail = exports.unicodeEmail = exports.rfc5322Email = exports.html5Email = exports.email = exports.uuid7 = exports.uuid6 = exports.uuid4 = exports.uuid = exports.guid = exports.extendedDuration = exports.duration = exports.nanoid = exports.ksuid = exports.xid = exports.ulid = exports.cuid2 = exports.cuid = void 0;
exports.sha512_base64url = exports.sha512_base64 = exports.sha512_hex = exports.sha384_base64url = exports.sha384_base64 = exports.sha384_hex = void 0;
exports.emoji = emoji;
exports.time = time;
exports.datetime = datetime;
const util = __importStar(require("./util.cjs"));
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
exports.cuid = /^[cC][0-9a-z]{6,}$/;
exports.cuid2 = /^[0-9a-z]+$/;
exports.ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
exports.xid = /^[0-9a-vA-V]{20}$/;
exports.ksuid = /^[A-Za-z0-9]{27}$/;
exports.nanoid = /^[a-zA-Z0-9_-]{21}$/;
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
exports.duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */
exports.extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
exports.guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
/** Returns a regex for validating an RFC 9562/4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
const uuid = (version) => {
if (!version)
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
exports.uuid = uuid;
exports.uuid4 = (0, exports.uuid)(4);
exports.uuid6 = (0, exports.uuid)(6);
exports.uuid7 = (0, exports.uuid)(7);
/** Practical email validation */
exports.email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */
exports.html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/** The classic emailregex.com regex for RFC 5322-compliant emails */
exports.rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */
exports.unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
exports.idnEmail = exports.unicodeEmail;
exports.browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
return new RegExp(_emoji, "u");
}
exports.ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
exports.ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
const mac = (delimiter) => {
const escapedDelim = util.escapeRegex(delimiter ?? ":");
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
exports.mac = mac;
exports.cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
exports.cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
exports.base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
exports.base64url = /^[A-Za-z0-9_-]*$/;
// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
exports.hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
exports.domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
exports.httpProtocol = /^https?$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
exports.e164 = /^\+[1-9]\d{6,14}$/;
// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
exports.date = new RegExp(`^${dateSource}$`);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
const regex = typeof args.precision === "number"
? args.precision === -1
? `${hhmm}`
: args.precision === 0
? `${hhmm}:[0-5]\\d`
: `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
: `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
function datetime(args) {
const time = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local)
opts.push("");
// if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
if (args.offset)
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
const timeRegex = `${time}(?:${opts.join("|")})`;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
const string = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
exports.string = string;
exports.bigint = /^-?\d+n?$/;
exports.integer = /^-?\d+$/;
exports.number = /^-?\d+(?:\.\d+)?$/;
exports.boolean = /^(?:true|false)$/i;
const _null = /^null$/i;
exports.null = _null;
const _undefined = /^undefined$/i;
exports.undefined = _undefined;
// regex for string with no uppercase letters
exports.lowercase = /^[^A-Z]*$/;
// regex for string with no lowercase letters
exports.uppercase = /^[^a-z]*$/;
// regex for hexadecimal strings (any length)
exports.hex = /^[0-9a-fA-F]*$/;
// Hash regexes for different algorithms and encodings
// Helper function to create base64 regex with exact length and padding
function fixedBase64(bodyLength, padding) {
return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
// Helper function to create base64url regex with exact length (no padding)
function fixedBase64url(length) {
return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
// MD5 (16 bytes): base64 = 24 chars total (22 + "==")
exports.md5_hex = /^[0-9a-fA-F]{32}$/;
exports.md5_base64 = fixedBase64(22, "==");
exports.md5_base64url = fixedBase64url(22);
// SHA1 (20 bytes): base64 = 28 chars total (27 + "=")
exports.sha1_hex = /^[0-9a-fA-F]{40}$/;
exports.sha1_base64 = fixedBase64(27, "=");
exports.sha1_base64url = fixedBase64url(27);
// SHA256 (32 bytes): base64 = 44 chars total (43 + "=")
exports.sha256_hex = /^[0-9a-fA-F]{64}$/;
exports.sha256_base64 = fixedBase64(43, "=");
exports.sha256_base64url = fixedBase64url(43);
// SHA384 (48 bytes): base64 = 64 chars total (no padding)
exports.sha384_hex = /^[0-9a-fA-F]{96}$/;
exports.sha384_base64 = fixedBase64(64, "");
exports.sha384_base64url = fixedBase64url(64);
// SHA512 (64 bytes): base64 = 88 chars total (86 + "==")
exports.sha512_hex = /^[0-9a-fA-F]{128}$/;
exports.sha512_base64 = fixedBase64(86, "==");
exports.sha512_base64url = fixedBase64url(86);

View File

@@ -0,0 +1,12 @@
import type * as JSONSchema from "../core/json-schema.js";
import { type $ZodRegistry } from "../core/registries.js";
import type { ZodType } from "./schemas.js";
type JSONSchemaVersion = "draft-2020-12" | "draft-7" | "draft-4" | "openapi-3.0";
interface FromJSONSchemaParams {
defaultTarget?: JSONSchemaVersion;
registry?: $ZodRegistry<any>;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export declare function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType;
export {};

View File

@@ -0,0 +1,5 @@
import * as ts from 'typescript';
import type { ParseSettings } from '../parseSettings';
import type { ASTAndNoProgram } from './shared';
export declare function createSourceFile(parseSettings: ParseSettings): ts.SourceFile;
export declare function createNoProgram(parseSettings: ParseSettings): ASTAndNoProgram;

View File

@@ -0,0 +1,12 @@
export var ScriptKind;
(function (ScriptKind) {
ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
ScriptKind[ScriptKind["JS"] = 1] = "JS";
ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
ScriptKind[ScriptKind["TS"] = 3] = "TS";
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind || (ScriptKind = {}));
//# sourceMappingURL=scriptKind.js.map

View File

@@ -0,0 +1,33 @@
'use strict'
let Container = require('./container')
let LazyResult, Processor
class Document extends Container {
constructor(defaults) {
// type needs to be passed to super, otherwise child roots won't be normalized correctly
super({ type: 'document', ...defaults })
if (!this.nodes) {
this.nodes = []
}
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor(), this, opts)
return lazy.stringify()
}
}
Document.registerLazyResult = dependant => {
LazyResult = dependant
}
Document.registerProcessor = dependant => {
Processor = dependant
}
module.exports = Document
Document.default = Document

View File

@@ -0,0 +1,30 @@
{
"name": "pump",
"version": "3.0.4",
"repository": "git://github.com/mafintosh/pump.git",
"license": "MIT",
"description": "pipe streams together and close all of them if one of them closes",
"browser": {
"fs": false
},
"imports": {
"fs": {
"bare": "./empty.js",
"default": "fs"
}
},
"keywords": [
"streams",
"pipe",
"destroy",
"callback"
],
"author": "Mathias Buus Madsen <mathiasbuus@gmail.com>",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
},
"scripts": {
"test": "node test-browser.js && node test-node.js"
}
}

View File

@@ -0,0 +1,494 @@
'use strict'
process.env.TZ = 'UTC'
const { Writable } = require('node:stream')
const { describe, test, afterEach, beforeEach } = require('node:test')
const pino = require('pino')
const semver = require('semver')
const serializers = pino.stdSerializers
const pinoPretty = require('../')
const _prettyFactory = pinoPretty.prettyFactory
function prettyFactory (opts) {
if (!opts) {
opts = { colorize: false }
} else if (!Object.prototype.hasOwnProperty.call(opts, 'colorize')) {
opts.colorize = false
}
return _prettyFactory(opts)
}
// All dates are computed from 'Fri, 30 Mar 2018 17:35:28 GMT'
const epoch = 1522431328992
const formattedEpoch = '17:35:28.992'
const pid = process.pid
describe('error like objects tests', () => {
beforeEach(() => {
Date.originalNow = Date.now
Date.now = () => epoch
})
afterEach(() => {
Date.now = Date.originalNow
delete Date.originalNow
})
test('pino transform prettifies Error', (t) => {
t.plan(2)
const pretty = prettyFactory()
const err = Error('hello world')
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 6)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
cb()
}
}))
log.info(err)
})
test('errorProps recognizes user specified properties', (t) => {
t.plan(3)
const pretty = prettyFactory({ errorProps: 'statusCode,originalStack' })
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
t.assert.match(formatted, /\s{4}error stack/)
t.assert.match(formatted, /"statusCode": 500/)
t.assert.match(formatted, /"originalStack": "original stack"/)
cb()
}
}))
const error = Error('error message')
error.stack = 'error stack'
error.statusCode = 500
error.originalStack = 'original stack'
log.error(error)
})
test('prettifies ignores undefined errorLikeObject', (t) => {
const pretty = prettyFactory()
pretty({ err: undefined })
pretty({ error: undefined })
})
test('prettifies Error in property within errorLikeObjectKeys', (t) => {
t.plan(8)
const pretty = prettyFactory({
errorLikeObjectKeys: ['err']
})
const err = Error('hello world')
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({ serializers: { err: serializers.err } }, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 6)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
t.assert.match(lines[1], /\s{4}err: {/)
t.assert.match(lines[2], /\s{6}"type": "Error",/)
t.assert.match(lines[3], /\s{6}"message": "hello world",/)
t.assert.match(lines[4], /\s{6}"stack":/)
t.assert.match(lines[5], /\s{6}Error: hello world/)
// Node 12 labels the test `<anonymous>`
t.assert.match(lines[6], /\s{10}at TestContext.<anonymous>/)
cb()
}
}))
log.info({ err })
})
test('prettifies Error in property with singleLine=true', (t) => {
// singleLine=true doesn't apply to errors
t.plan(8)
const pretty = prettyFactory({
singleLine: true,
errorLikeObjectKeys: ['err']
})
const err = Error('hello world')
const expected = [
'{"extra":{"a":1,"b":2}}',
err.message,
...err.stack.split('\n')
]
const log = pino({ serializers: { err: serializers.err } }, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 5)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world {"extra":{"a":1,"b":2}}`)
t.assert.match(lines[1], /\s{4}err: {/)
t.assert.match(lines[2], /\s{6}"type": "Error",/)
t.assert.match(lines[3], /\s{6}"message": "hello world",/)
t.assert.match(lines[4], /\s{6}"stack":/)
t.assert.match(lines[5], /\s{6}Error: hello world/)
// Node 12 labels the test `<anonymous>`
t.assert.match(lines[6], /\s{10}at TestContext.<anonymous>/)
cb()
}
}))
log.info({ err, extra: { a: 1, b: 2 } })
})
test('prettifies Error in property within errorLikeObjectKeys with custom function', (t) => {
t.plan(4)
const pretty = prettyFactory({
errorLikeObjectKeys: ['err'],
customPrettifiers: {
err: val => `error is ${val.message}`
}
})
const err = Error('hello world')
err.stack = 'Error: hello world\n at anonymous (C:\\project\\node_modules\\example\\index.js)'
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({ serializers: { err: serializers.err } }, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, 3)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
t.assert.strictEqual(lines[1], ' err: error is hello world')
t.assert.strictEqual(lines[2], '')
cb()
}
}))
log.info({ err })
})
test('prettifies Error in property within errorLikeObjectKeys when stack has escaped characters', (t) => {
t.plan(8)
const pretty = prettyFactory({
errorLikeObjectKeys: ['err']
})
const err = Error('hello world')
err.stack = 'Error: hello world\n at anonymous (C:\\project\\node_modules\\example\\index.js)'
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({ serializers: { err: serializers.err } }, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 6)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
t.assert.match(lines[1], /\s{4}err: {$/)
t.assert.match(lines[2], /\s{6}"type": "Error",$/)
t.assert.match(lines[3], /\s{6}"message": "hello world",$/)
t.assert.match(lines[4], /\s{6}"stack":$/)
t.assert.match(lines[5], /\s{10}Error: hello world$/)
t.assert.match(lines[6], /\s{10}at anonymous \(C:\\project\\node_modules\\example\\index.js\)$/)
cb()
}
}))
log.info({ err })
})
test('prettifies Error in property within errorLikeObjectKeys when stack is not the last property', (t) => {
t.plan(9)
const pretty = prettyFactory({
errorLikeObjectKeys: ['err']
})
const err = Error('hello world')
err.anotherField = 'dummy value'
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({ serializers: { err: serializers.err } }, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 7)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
t.assert.match(lines[1], /\s{4}err: {/)
t.assert.match(lines[2], /\s{6}"type": "Error",/)
t.assert.match(lines[3], /\s{6}"message": "hello world",/)
t.assert.match(lines[4], /\s{6}"stack":/)
t.assert.match(lines[5], /\s{6}Error: hello world/)
// Node 12 labels the test `<anonymous>`
t.assert.match(lines[6], /\s{10}at TestContext.<anonymous>/)
t.assert.match(lines[lines.length - 3], /\s{6}"anotherField": "dummy value"/)
cb()
}
}))
log.info({ err })
})
test('errorProps flag with "*" (print all nested props)', function (t) {
const pretty = prettyFactory({ errorProps: '*' })
const expectedLines = [
' err: {',
' "type": "Error",',
' "message": "error message",',
' "stack":',
' error stack',
' "statusCode": 500,',
' "originalStack": "original stack",',
' "dataBaseSpecificError": {',
' "erroMessage": "some database error message",',
' "evenMoreSpecificStuff": {',
' "someErrorRelatedObject": "error"',
' }',
' }',
' }'
]
t.plan(expectedLines.length)
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
lines.shift(); lines.pop()
for (let i = 0; i < lines.length; i += 1) {
t.assert.strictEqual(lines[i], expectedLines[i])
}
cb()
}
}))
const error = Error('error message')
error.stack = 'error stack'
error.statusCode = 500
error.originalStack = 'original stack'
error.dataBaseSpecificError = {
erroMessage: 'some database error message',
evenMoreSpecificStuff: {
someErrorRelatedObject: 'error'
}
}
log.error(error)
})
test('prettifies legacy error object at top level when singleLine=true', function (t) {
t.plan(4)
const pretty = prettyFactory({ singleLine: true })
const err = Error('hello world')
const expected = err.stack.split('\n')
expected.unshift(err.message)
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 1)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): ${expected[0]}`)
t.assert.strictEqual(lines[1], ` ${expected[1]}`)
t.assert.strictEqual(lines[2], ` ${expected[2]}`)
cb()
}
}))
log.info({ type: 'Error', stack: err.stack, msg: err.message })
})
test('errorProps: legacy error object at top level', function (t) {
const pretty = prettyFactory({ errorProps: '*' })
const expectedLines = [
'INFO:',
' error stack',
' message: hello message',
' statusCode: 500',
' originalStack: original stack',
' dataBaseSpecificError: {',
' errorMessage: "some database error message"',
' evenMoreSpecificStuff: {',
' "someErrorRelatedObject": "error"',
' }',
' }',
''
]
t.plan(expectedLines.length)
const error = {}
error.level = 30
error.message = 'hello message'
error.type = 'Error'
error.stack = 'error stack'
error.statusCode = 500
error.originalStack = 'original stack'
error.dataBaseSpecificError = {
errorMessage: 'some database error message',
evenMoreSpecificStuff: {
someErrorRelatedObject: 'error'
}
}
const formatted = pretty(JSON.stringify(error))
const lines = formatted.split('\n')
for (let i = 0; i < lines.length; i += 1) {
t.assert.strictEqual(lines[i], expectedLines[i])
}
})
test('errorProps flag with a single property', function (t) {
const pretty = prettyFactory({ errorProps: 'originalStack' })
const expectedLines = [
'INFO:',
' error stack',
' originalStack: original stack',
''
]
t.plan(expectedLines.length)
const error = {}
error.level = 30
error.message = 'hello message'
error.type = 'Error'
error.stack = 'error stack'
error.statusCode = 500
error.originalStack = 'original stack'
error.dataBaseSpecificError = {
erroMessage: 'some database error message',
evenMoreSpecificStuff: {
someErrorRelatedObject: 'error'
}
}
const formatted = pretty(JSON.stringify(error))
const lines = formatted.split('\n')
for (let i = 0; i < lines.length; i += 1) {
t.assert.strictEqual(lines[i], expectedLines[i])
}
})
test('errorProps flag with a single property non existent', function (t) {
const pretty = prettyFactory({ errorProps: 'originalStackABC' })
const expectedLines = [
'INFO:',
' error stack',
''
]
t.plan(expectedLines.length)
const error = {}
error.level = 30
error.message = 'hello message'
error.type = 'Error'
error.stack = 'error stack'
error.statusCode = 500
error.originalStack = 'original stack'
error.dataBaseSpecificError = {
erroMessage: 'some database error message',
evenMoreSpecificStuff: {
someErrorRelatedObject: 'error'
}
}
const formatted = pretty(JSON.stringify(error))
const lines = formatted.split('\n')
for (let i = 0; i < lines.length; i += 1) {
t.assert.strictEqual(lines[i], expectedLines[i])
}
})
test('handles errors with a null stack', (t) => {
t.plan(2)
const pretty = prettyFactory()
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
t.assert.match(formatted, /\s{4}message: "foo"/)
t.assert.match(formatted, /\s{4}stack: null/)
cb()
}
}))
const error = { message: 'foo', stack: null }
log.error(error)
})
test('handles errors with a null stack for Error object', (t) => {
const pretty = prettyFactory()
const expectedLines = [
' "type": "Error",',
' "message": "error message",',
' "stack":',
' ',
' "some": "property"'
]
t.plan(expectedLines.length)
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
lines.shift(); lines.shift(); lines.pop(); lines.pop()
for (let i = 0; i < lines.length; i += 1) {
t.assert.ok(lines[i].includes(expectedLines[i]))
}
cb()
}
}))
const error = Error('error message')
error.stack = null
error.some = 'property'
log.error(error)
})
})
if (semver.gte(pino.version, '8.21.0')) {
describe('using pino config', () => {
beforeEach(() => {
Date.originalNow = Date.now
Date.now = () => epoch
})
afterEach(() => {
Date.now = Date.originalNow
delete Date.originalNow
})
test('prettifies Error in custom errorKey', (t) => {
t.plan(8)
const destination = new Writable({
write (chunk, enc, cb) {
const formatted = chunk.toString()
const lines = formatted.split('\n')
t.assert.strictEqual(lines.length, expected.length + 7)
t.assert.strictEqual(lines[0], `[${formattedEpoch}] INFO (${pid}): hello world`)
t.assert.match(lines[1], /\s{4}customErrorKey: {/)
t.assert.match(lines[2], /\s{6}"type": "Error",/)
t.assert.match(lines[3], /\s{6}"message": "hello world",/)
t.assert.match(lines[4], /\s{6}"stack":/)
t.assert.match(lines[5], /\s{6}Error: hello world/)
// Node 12 labels the test `<anonymous>`
t.assert.match(lines[6], /\s{10}(at Test.await t.test|at Test.<anonymous>)/)
cb()
}
})
const pretty = pinoPretty({
destination,
colorize: false
})
const log = pino({ errorKey: 'customErrorKey' }, pretty)
const err = Error('hello world')
const expected = err.stack.split('\n')
log.info({ customErrorKey: err })
})
})
}

View File

@@ -0,0 +1,192 @@
//#region src/utils/code-frame.ts
function spaces(index) {
let result = "";
while (index--) result += " ";
return result;
}
function tabsToSpaces(value) {
return value.replace(/^\t+/, (match) => match.split(" ").join(" "));
}
const LINE_TRUNCATE_LENGTH = 120;
const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
const ELLIPSIS = "...";
function getCodeFrame(source, line, column) {
let lines = source.split("\n");
if (line > lines.length) return "";
const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length + MIN_CHARACTERS_SHOWN_AFTER_LOCATION + 3, LINE_TRUNCATE_LENGTH);
const frameStart = Math.max(0, line - 3);
let frameEnd = Math.min(line + 2, lines.length);
lines = lines.slice(frameStart, frameEnd);
while (!/\S/.test(lines[lines.length - 1])) {
lines.pop();
frameEnd -= 1;
}
const digits = String(frameEnd).length;
return lines.map((sourceLine, index) => {
const isErrorLine = frameStart + index + 1 === line;
let lineNumber = String(index + frameStart + 1);
while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`;
let displayedLine = tabsToSpaces(sourceLine);
if (displayedLine.length > maxLineLength) displayedLine = `${displayedLine.slice(0, maxLineLength - 3)}${ELLIPSIS}`;
if (isErrorLine) {
const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + "^";
return `${lineNumber}: ${displayedLine}\n${indicator}`;
}
return `${lineNumber}: ${displayedLine}`;
}).join("\n");
}
//#endregion
//#region src/log/locate-character/index.js
/** @typedef {import('./types').Location} Location */
/**
* @param {import('./types').Range} range
* @param {number} index
*/
function rangeContains(range, index) {
return range.start <= index && index < range.end;
}
/**
* @param {string} source
* @param {import('./types').Options} [options]
*/
function getLocator(source, options = {}) {
const { offsetLine = 0, offsetColumn = 0 } = options;
let start = 0;
const ranges = source.split("\n").map((line, i) => {
const end = start + line.length + 1;
/** @type {import('./types').Range} */
const range = {
start,
end,
line: i
};
start = end;
return range;
});
let i = 0;
/**
* @param {string | number} search
* @param {number} [index]
* @returns {Location | undefined}
*/
function locator(search, index) {
if (typeof search === "string") search = source.indexOf(search, index ?? 0);
if (search === -1) return void 0;
let range = ranges[i];
const d = search >= range.end ? 1 : -1;
while (range) {
if (rangeContains(range, search)) return {
line: offsetLine + range.line,
column: offsetColumn + search - range.start,
character: search
};
i += d;
range = ranges[i];
}
}
return locator;
}
/**
* @param {string} source
* @param {string | number} search
* @param {import('./types').Options} [options]
* @returns {Location | undefined}
*/
function locate(source, search, options) {
return getLocator(source, options)(search, options && options.startIndex);
}
//#endregion
//#region src/log/logs.ts
const INVALID_LOG_POSITION = "INVALID_LOG_POSITION";
const PLUGIN_ERROR = "PLUGIN_ERROR";
const INPUT_HOOK_IN_OUTPUT_PLUGIN = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
const CYCLE_LOADING = "CYCLE_LOADING";
const MULTIPLE_WATCHER_OPTION = "MULTIPLE_WATCHER_OPTION";
const PARSE_ERROR = "PARSE_ERROR";
const VALIDATION_ERROR = "VALIDATION_ERROR";
function logParseError(message, id, pos) {
return {
code: PARSE_ERROR,
id,
message,
pos
};
}
function logFailedValidation(message) {
return {
code: VALIDATION_ERROR,
message
};
}
function logInvalidLogPosition(pluginName) {
return {
code: INVALID_LOG_POSITION,
message: `Plugin "${pluginName}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
};
}
function logInputHookInOutputPlugin(pluginName, hookName) {
return {
code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
};
}
function logCycleLoading(pluginName, moduleId) {
return {
code: CYCLE_LOADING,
message: `Found the module "${moduleId}" cycle loading at ${pluginName} plugin, it maybe blocking fetching modules.`
};
}
function logMultipleWatcherOption() {
return {
code: MULTIPLE_WATCHER_OPTION,
message: `Found multiple watcher options at watch options, using first one to start watcher.`
};
}
function logPluginError(error, plugin, { hook, id } = {}) {
try {
const code = error.code;
if (!error.pluginCode && code != null && (typeof code !== "string" || !code.startsWith("PLUGIN_"))) error.pluginCode = code;
error.code = PLUGIN_ERROR;
error.plugin = plugin;
if (hook) error.hook = hook;
if (id) error.id = id;
} catch (_) {} finally {
return error;
}
}
function error(base) {
if (!(base instanceof Error)) {
base = Object.assign(new Error(base.message), base);
Object.defineProperty(base, "name", {
value: "RolldownError",
writable: true
});
}
throw base;
}
function augmentCodeLocation(properties, pos, source, id) {
if (typeof pos === "object") {
const { line, column } = pos;
properties.loc = {
column,
file: id,
line
};
} else {
properties.pos = pos;
const location = locate(source, pos, { offsetLine: 1 });
if (!location) return;
const { line, column } = location;
properties.loc = {
column,
file: id,
line
};
}
if (properties.frame === void 0) {
const { line, column } = properties.loc;
properties.frame = getCodeFrame(source, line, column);
}
}
//#endregion
export { logInputHookInOutputPlugin as a, logParseError as c, getCodeFrame as d, logFailedValidation as i, logPluginError as l, error as n, logInvalidLogPosition as o, logCycleLoading as r, logMultipleWatcherOption as s, augmentCodeLocation as t, locate as u };

View File

@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2023_collection = void 0;
const base_config_1 = require("./base-config");
exports.es2023_collection = {
libs: [],
variables: [['WeakKeyTypes', base_config_1.TYPE]],
};

View File

@@ -0,0 +1,450 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const nested = z.object({
name: z.string(),
age: z.number(),
outer: z.object({
inner: z.string(),
}),
array: z.array(z.object({ asdf: z.string() })),
});
test("shallow inference", () => {
const shallow = nested.partial();
type shallow = z.infer<typeof shallow>;
expectTypeOf<shallow>().toEqualTypeOf<{
name?: string | undefined;
age?: number | undefined;
outer?: { inner: string } | undefined;
array?: { asdf: string }[] | undefined;
}>();
});
test("shallow partial parse", () => {
const shallow = nested.partial();
shallow.parse({});
shallow.parse({
name: "asdf",
age: 23143,
});
});
test("required", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
nullableField: z.number().nullable(),
nullishField: z.string().nullish(),
});
const requiredObject = object.required();
expect(requiredObject.shape.name).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.name.unwrap()).toBeInstanceOf(z.ZodString);
expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.age.unwrap()).toBeInstanceOf(z.ZodOptional);
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.field.unwrap()).toBeInstanceOf(z.ZodDefault);
expect(requiredObject.shape.nullableField).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.nullableField.unwrap()).toBeInstanceOf(z.ZodNullable);
expect(requiredObject.shape.nullishField).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.nullishField.unwrap()).toBeInstanceOf(z.ZodOptional);
expect(requiredObject.shape.nullishField.unwrap().unwrap()).toBeInstanceOf(z.ZodNullable);
});
test("required inference", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
nullableField: z.number().nullable(),
nullishField: z.string().nullish(),
});
const requiredObject = object.required();
type required = z.infer<typeof requiredObject>;
type expected = {
name: string;
age: number;
field: string;
nullableField: number | null;
nullishField: string | null;
};
expectTypeOf<expected>().toEqualTypeOf<required>();
});
test("required with mask", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string().optional(),
});
const requiredObject = object.required({ age: true });
expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString);
expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional);
});
test("required with mask -- ignore falsy values", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string().optional(),
});
// @ts-expect-error
const requiredObject = object.required({ age: true, country: false });
expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString);
expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional);
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional);
});
test("partial with mask", async () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string(),
});
const masked = object.partial({ age: true, field: true, name: true }).strict();
expect(masked.shape.name).toBeInstanceOf(z.ZodOptional);
expect(masked.shape.age).toBeInstanceOf(z.ZodOptional);
expect(masked.shape.field).toBeInstanceOf(z.ZodOptional);
expect(masked.shape.country).toBeInstanceOf(z.ZodString);
masked.parse({ country: "US" });
await masked.parseAsync({ country: "US" });
});
test("partial with mask -- ignore falsy values", async () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string(),
});
// @ts-expect-error
const masked = object.partial({ name: true, country: false }).strict();
expect(masked.shape.name).toBeInstanceOf(z.ZodOptional);
expect(masked.shape.age).toBeInstanceOf(z.ZodOptional);
expect(masked.shape.field).toBeInstanceOf(z.ZodDefault);
expect(masked.shape.country).toBeInstanceOf(z.ZodString);
masked.parse({ country: "US" });
await masked.parseAsync({ country: "US" });
});
test("catch/prefault/default", () => {
const mySchema = z.object({
a: z.string().catch("catch value").optional(),
b: z.string().default("default value").optional(),
c: z.string().prefault("prefault value").optional(),
d: z.string().catch("catch value"),
e: z.string().default("default value"),
f: z.string().prefault("prefault value"),
});
// Catch (d) and default/prefault (b, c, e, f) handle absent keys gracefully.
// `a: catch().optional()` short-circuits to undefined when the original
// input was undefined, so the property is omitted from the output. All
// other catch/default/prefault keys produce their fallback values.
expect(mySchema.parse({})).toMatchInlineSnapshot(`
{
"b": "default value",
"c": "prefault value",
"d": "catch value",
"e": "default value",
"f": "prefault value",
}
`);
expect(mySchema.parse({}, { jitless: true })).toMatchInlineSnapshot(`
{
"b": "default value",
"c": "prefault value",
"d": "catch value",
"e": "default value",
"f": "prefault value",
}
`);
expect(mySchema.parse({ d: undefined })).toMatchInlineSnapshot(`
{
"b": "default value",
"c": "prefault value",
"d": "catch value",
"e": "default value",
"f": "prefault value",
}
`);
expect(mySchema.parse({ d: undefined }, { jitless: true })).toMatchInlineSnapshot(`
{
"b": "default value",
"c": "prefault value",
"d": "catch value",
"e": "default value",
"f": "prefault value",
}
`);
});
test("handleOptionalObjectResult branches", () => {
const mySchema = z.object({
// Branch: input[key] === undefined, key not in input, caught error
caughtMissing: z.string().catch("caught").optional(),
// Branch: input[key] === undefined, key in input, caught error
caughtUndefined: z.string().catch("caught").optional(),
// Branch: input[key] === undefined, key not in input, validation issues
issueMissing: z.string().min(5).optional(),
// Branch: input[key] === undefined, key in input, validation issues
issueUndefined: z.string().min(5).optional(),
// Branch: input[key] === undefined, validation returns undefined
validUndefined: z.string().optional(),
// Branch: input[key] === undefined, non-undefined result (default/transform)
defaultValue: z.string().default("default").optional(),
// Branch: input[key] defined, caught error
caughtDefined: z.string().catch("caught").optional(),
// Branch: input[key] defined, validation issues
issueDefined: z.string().min(5).optional(),
// Branch: input[key] defined, validation returns undefined
validDefinedUndefined: z
.string()
.transform(() => undefined)
.optional(),
// Branch: input[key] defined, non-undefined value
validDefined: z.string().optional(),
});
// Test input[key] === undefined cases
const result1 = mySchema.parse(
{
// caughtMissing: not present (key not in input)
caughtUndefined: undefined, // key in input
// issueMissing: not present (key not in input)
issueUndefined: undefined, // key in input
validUndefined: undefined,
// defaultValue: not present, will get default
},
{ jitless: true }
);
expect(result1).toEqual({
caughtUndefined: undefined,
issueUndefined: undefined,
validUndefined: undefined,
defaultValue: "default",
});
// Test input[key] defined cases (successful)
const result2 = mySchema.parse(
{
caughtDefined: 123, // invalid type, should catch
validDefinedUndefined: "test", // transforms to undefined
validDefined: "valid", // valid value
},
{ jitless: true }
);
expect(result2).toEqual({
caughtDefined: "caught",
validDefinedUndefined: undefined,
validDefined: "valid",
defaultValue: "default",
});
// Test validation issues are properly reported (input[key] defined, validation fails)
expect(() =>
mySchema.parse(
{
issueDefined: "abc", // too short
},
{ jitless: true }
)
).toThrow();
});
test("fastpass vs non-fastpass consistency", () => {
const mySchema = z.object({
caughtMissing: z.string().catch("caught").optional(),
caughtUndefined: z.string().catch("caught").optional(),
issueMissing: z.string().min(5).optional(),
issueUndefined: z.string().min(5).optional(),
validUndefined: z.string().optional(),
defaultValue: z.string().default("default").optional(),
caughtDefined: z.string().catch("caught").optional(),
validDefinedUndefined: z
.string()
.transform(() => undefined)
.optional(),
validDefined: z.string().optional(),
});
const input = {
caughtUndefined: undefined,
issueUndefined: undefined,
validUndefined: undefined,
caughtDefined: 123,
validDefinedUndefined: "test",
validDefined: "valid",
};
// Test both paths produce identical results
const jitlessResult = mySchema.parse(input, { jitless: true });
const fastpassResult = mySchema.parse(input);
expect(jitlessResult).toEqual(fastpassResult);
expect(jitlessResult).toEqual({
caughtUndefined: undefined,
issueUndefined: undefined,
validUndefined: undefined,
defaultValue: "default",
caughtDefined: "caught",
validDefinedUndefined: undefined,
validDefined: "valid",
});
});
test("optional with check", () => {
const baseSchema = z
.string()
.optional()
.check(({ value, ...ctx }) => {
ctx.issues.push({
code: "custom",
input: value,
message: "message",
});
});
// this correctly fails
expect(baseSchema.safeParse(undefined)).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "message",
"path": []
}
]],
"success": false,
}
`);
const schemaObject = z.object({
date: baseSchema,
});
expect(schemaObject.safeParse({ date: undefined })).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "message",
"path": [
"date"
]
}
]],
"success": false,
}
`);
});
test("partial - throws error on schema with refinements", () => {
const baseSchema = z.object({
id: z.string(),
name: z.string(),
items: z.string().array(),
});
const refinedSchema = baseSchema.superRefine((val, ctx) => {
if (val.items.length === 0) {
ctx.addIssue({
message: "Must have at least one item",
code: "custom",
path: ["items"],
});
}
});
expect(() => refinedSchema.partial()).toThrow(".partial() cannot be used on object schemas containing refinements");
});
test("partial - throws error on schema with refine", () => {
const baseSchema = z.object({
password: z.string(),
confirmPassword: z.string(),
});
const refinedSchema = baseSchema.refine((data) => data.password === data.confirmPassword, {
message: "Passwords must match",
});
expect(() => refinedSchema.partial()).toThrow(".partial() cannot be used on object schemas containing refinements");
});
test("required - preserves refinements", () => {
const baseSchema = z.object({
name: z.string().optional(),
age: z.number().optional(),
});
const refinedSchema = baseSchema.superRefine((val, ctx) => {
if (val.name === "admin") {
ctx.addIssue({
message: "Name cannot be admin",
code: "custom",
path: ["name"],
});
}
});
const requiredSchema = refinedSchema.required();
// The refinement should still be applied
const result = requiredSchema.safeParse({ name: "admin", age: 25 });
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues[0].message).toBe("Name cannot be admin");
}
// Valid data should pass
const validResult = requiredSchema.safeParse({ name: "user", age: 25 });
expect(validResult.success).toBe(true);
});
test("required - refinement is executed on required schema", () => {
const baseSchema = z.object({
password: z.string().optional(),
confirmPassword: z.string().optional(),
});
const refinedSchema = baseSchema.refine((data) => data.password === data.confirmPassword, {
message: "Passwords must match",
});
const requiredSchema = refinedSchema.required();
// Mismatched passwords should fail refinement
const result = requiredSchema.safeParse({ password: "abc", confirmPassword: "xyz" });
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues[0].message).toBe("Passwords must match");
}
// Matching passwords should pass
const validResult = requiredSchema.safeParse({ password: "abc", confirmPassword: "abc" });
expect(validResult.success).toBe(true);
});

View File

@@ -0,0 +1,207 @@
declare module 'worker_threads' {
import { Context } from 'vm';
import EventEmitter = require('events');
import { Readable, Writable } from 'stream';
import { promises } from 'fs';
const isMainThread: boolean;
const parentPort: null | MessagePort;
const resourceLimits: ResourceLimits;
const SHARE_ENV: unique symbol;
const threadId: number;
const workerData: any;
class MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
}
type TransferListItem = ArrayBuffer | MessagePort | promises.FileHandle;
class MessagePort extends EventEmitter {
close(): void;
postMessage(value: any, transferList?: ReadonlyArray<TransferListItem>): void;
ref(): void;
unref(): void;
start(): void;
addListener(event: "close", listener: () => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "close"): boolean;
emit(event: "message", value: any): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "close", listener: () => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "close", listener: () => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
interface WorkerOptions {
eval?: boolean | undefined;
env?: NodeJS.ProcessEnv | typeof SHARE_ENV | undefined;
workerData?: any;
stdin?: boolean | undefined;
stdout?: boolean | undefined;
stderr?: boolean | undefined;
execArgv?: string[] | undefined;
resourceLimits?: ResourceLimits | undefined;
/**
* Additional data to send in the first worker message.
*/
transferList?: TransferListItem[] | undefined;
trackUnmanagedFds?: boolean | undefined;
}
interface ResourceLimits {
/**
* The maximum size of a heap space for recently created objects.
*/
maxYoungGenerationSizeMb?: number | undefined;
/**
* The maximum size of the main heap in MB.
*/
maxOldGenerationSizeMb?: number | undefined;
/**
* The size of a pre-allocated memory range used for generated code.
*/
codeRangeSizeMb?: number | undefined;
/**
* The default maximum stack size for the thread. Small values may lead to unusable Worker instances.
* @default 4
*/
stackSizeMb?: number | undefined;
}
class Worker extends EventEmitter {
readonly stdin: Writable | null;
readonly stdout: Readable;
readonly stderr: Readable;
readonly threadId: number;
readonly resourceLimits?: ResourceLimits | undefined;
constructor(filename: string, options?: WorkerOptions);
postMessage(value: any, transferList?: ReadonlyArray<TransferListItem>): void;
ref(): void;
unref(): void;
/**
* Stop all JavaScript execution in the worker thread as soon as possible.
* Returns a Promise for the exit code that is fulfilled when the `exit` event is emitted.
*/
terminate(): Promise<number>;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (exitCode: number) => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: "messageerror", listener: (error: Error) => void): this;
addListener(event: "online", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "error", err: Error): boolean;
emit(event: "exit", exitCode: number): boolean;
emit(event: "message", value: any): boolean;
emit(event: "messageerror", error: Error): boolean;
emit(event: "online"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "error", listener: (err: Error) => void): this;
on(event: "exit", listener: (exitCode: number) => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: "messageerror", listener: (error: Error) => void): this;
on(event: "online", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "exit", listener: (exitCode: number) => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: "messageerror", listener: (error: Error) => void): this;
once(event: "online", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "exit", listener: (exitCode: number) => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: "messageerror", listener: (error: Error) => void): this;
prependListener(event: "online", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "exit", listener: (exitCode: number) => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
prependOnceListener(event: "online", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "exit", listener: (exitCode: number) => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: "messageerror", listener: (error: Error) => void): this;
removeListener(event: "online", listener: () => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "error", listener: (err: Error) => void): this;
off(event: "exit", listener: (exitCode: number) => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: "messageerror", listener: (error: Error) => void): this;
off(event: "online", listener: () => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
/**
* Mark an object as not transferable.
* If `object` occurs in the transfer list of a `port.postMessage()` call, it will be ignored.
*
* In particular, this makes sense for objects that can be cloned, rather than transferred,
* and which are used by other objects on the sending side. For example, Node.js marks
* the `ArrayBuffer`s it uses for its Buffer pool with this.
*
* This operation cannot be undone.
*/
function markAsUntransferable(object: object): void;
/**
* Transfer a `MessagePort` to a different `vm` Context. The original `port`
* object will be rendered unusable, and the returned `MessagePort` instance will
* take its place.
*
* The returned `MessagePort` will be an object in the target context, and will
* inherit from its global `Object` class. Objects passed to the
* `port.onmessage()` listener will also be created in the target context
* and inherit from its global `Object` class.
*
* However, the created `MessagePort` will no longer inherit from
* `EventEmitter`, and only `port.onmessage()` can be used to receive
* events using it.
*/
function moveMessagePortToContext(port: MessagePort, context: Context): MessagePort;
/**
* Receive a single message from a given `MessagePort`. If no message is available,
* `undefined` is returned, otherwise an object with a single `message` property
* that contains the message payload, corresponding to the oldest message in the
* `MessagePort`s queue.
*/
function receiveMessageOnPort(port: MessagePort): { message: any } | undefined;
}

View File

@@ -0,0 +1,109 @@
import type { JsxEmit } from "#enums/jsxEmit";
import type { ModuleDetectionKind } from "#enums/moduleDetectionKind";
import type { ModuleKind } from "#enums/moduleKind";
import type { ModuleResolutionKind } from "#enums/moduleResolutionKind";
import type { NewLineKind } from "#enums/newLineKind";
import type { ScriptTarget } from "#enums/scriptTarget";
export interface CompilerOptions {
allowJs?: boolean;
allowArbitraryExtensions?: boolean;
allowImportingTsExtensions?: boolean;
allowNonTsExtensions?: boolean;
allowUmdGlobalAccess?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
assumeChangesOnlyAffectDirectDependencies?: boolean;
checkJs?: boolean;
customConditions?: string[];
composite?: boolean;
emitDeclarationOnly?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
declaration?: boolean;
declarationDir?: string;
declarationMap?: boolean;
deduplicatePackages?: boolean;
disableSizeLimit?: boolean;
disableSourceOfProjectReferenceRedirect?: boolean;
disableSolutionSearching?: boolean;
disableReferencedProjectLoad?: boolean;
erasableSyntaxOnly?: boolean;
exactOptionalPropertyTypes?: boolean;
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
isolatedModules?: boolean;
isolatedDeclarations?: boolean;
ignoreConfig?: boolean;
ignoreDeprecations?: string;
importHelpers?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
init?: boolean;
incremental?: boolean;
jsx?: JsxEmit;
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
lib?: string[];
libReplacement?: boolean;
locale?: string;
mapRoot?: string;
module?: ModuleKind;
moduleResolution?: ModuleResolutionKind;
moduleSuffixes?: string[];
moduleDetection?: ModuleDetectionKind;
newLine?: NewLineKind;
noEmit?: boolean;
noCheck?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noImplicitReturns?: boolean;
noEmitHelpers?: boolean;
noLib?: boolean;
noPropertyAccessFromIndexSignature?: boolean;
noUncheckedIndexedAccess?: boolean;
noEmitOnError?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
noResolve?: boolean;
noImplicitOverride?: boolean;
noUncheckedSideEffectImports?: boolean;
outDir?: string;
paths?: Record<string, string[]>;
preserveConstEnums?: boolean;
preserveSymlinks?: boolean;
project?: string;
resolveJsonModule?: boolean;
resolvePackageJsonExports?: boolean;
resolvePackageJsonImports?: boolean;
removeComments?: boolean;
rewriteRelativeImportExtensions?: boolean;
reactNamespace?: string;
rootDir?: string;
rootDirs?: string[];
skipLibCheck?: boolean;
stableTypeOrdering?: boolean;
strict?: boolean;
strictBindCallApply?: boolean;
strictBuiltinIteratorReturn?: boolean;
strictFunctionTypes?: boolean;
strictNullChecks?: boolean;
strictPropertyInitialization?: boolean;
stripInternal?: boolean;
skipDefaultLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
suppressOutputPathCheck?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
tsBuildInfoFile?: string;
typeRoots?: string[];
types?: string[];
useDefineForClassFields?: boolean;
useUnknownInCatchVariables?: boolean;
verbatimModuleSyntax?: boolean;
maxNodeModuleJsDepth?: number;
}
//# sourceMappingURL=compilerOptions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAiC,IAAI,EAAW,KAAK,KAAK,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAElG,qBAAa,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACxD,KAAK,EAAE,CAAC,CAAC;IACT,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;gBAEd,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK;IAsBpC,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI;IAKxB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI;IASjC,MAAM,IAAI,UAAU;IAKpB,UAAU,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAajC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;IAGhB,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,IAAI,EAAE;IACjB,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,GAAG,UAAU,CAAC;IACtD,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;CAEM,CAAC"}

View File

@@ -0,0 +1,4 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"forInViolation", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,30 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.describeFilePath = describeFilePath;
const node_path_1 = __importDefault(require("node:path"));
function describeFilePath(filePath, tsconfigRootDir) {
// If the TSConfig root dir is a parent of the filePath, use
// `<tsconfigRootDir>` as a prefix for the path.
const relative = node_path_1.default.relative(tsconfigRootDir, filePath);
if (relative && !relative.startsWith('..') && !node_path_1.default.isAbsolute(relative)) {
return `<tsconfigRootDir>/${relative}`;
}
// Root-like Mac/Linux (~/*, ~*) or Windows (C:/*, /) paths that aren't
// relative to the TSConfig root dir should be fully described.
// This avoids strings like <tsconfigRootDir>/../../../../repo/file.ts.
// https://github.com/typescript-eslint/typescript-eslint/issues/6289
if (/^[(\w+:)\\/~]/.test(filePath)) {
return filePath;
}
// Similarly, if the relative path would contain a lot of ../.., then
// ignore it and print the file path directly.
if (/\.\.[/\\]\.\./.test(relative)) {
return filePath;
}
// Lastly, since we've eliminated all special cases, we know the cleanest
// path to print is probably the prefixed relative one.
return `<tsconfigRootDir>/${relative}`;
}

View File

@@ -0,0 +1,69 @@
'use strict'
const { test } = require('node:test')
const { createCopier } = require('fast-copy')
const fastCopy = createCopier({})
const interpretConditionals = require('./interpret-conditionals')
const logData = {
level: 30,
data1: {
data2: 'bar'
},
msg: 'foo'
}
test('interpretConditionals translates if / else statement to found property value', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level} - {if data1.data2}{data1.data2}{end}', log), '{level} - bar')
})
test('interpretConditionals translates if / else statement to found property value and leave unmatched property key untouched', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level} - {if data1.data2}{data1.data2} ({msg}){end}', log), '{level} - bar ({msg})')
})
test('interpretConditionals removes non-terminated if statements', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level} - {if data1.data2}{data1.data2}', log), '{level} - {data1.data2}')
})
test('interpretConditionals removes floating end statements', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level} - {data1.data2}{end}', log), '{level} - {data1.data2}')
})
test('interpretConditionals removes floating end statements within translated if / end statements', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level} - {if msg}({msg}){end}{end}', log), '{level} - (foo)')
})
test('interpretConditionals removes if / end blocks if existent condition key does not match existent property key', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level}{if msg}{data1.data2}{end}', log), '{level}')
})
test('interpretConditionals removes if / end blocks if non-existent condition key does not match existent property key', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level}{if foo}{msg}{end}', log), '{level}')
})
test('interpretConditionals removes if / end blocks if existent condition key does not match non-existent property key', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level}{if msg}{foo}{end}', log), '{level}')
})
test('interpretConditionals removes if / end blocks if non-existent condition key does not match non-existent property key', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level}{if foo}{bar}{end}', log), '{level}')
})
test('interpretConditionals removes if / end blocks if nested condition key does not match property key', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{level}{if data1.msg}{data1.data2}{end}', log), '{level}')
})
test('interpretConditionals removes nested if / end statement blocks', t => {
const log = fastCopy(logData)
t.assert.strictEqual(interpretConditionals('{if msg}{if data1.data2}{msg}{data1.data2}{end}{end}', log), 'foo{data1.data2}')
})

View File

@@ -0,0 +1,488 @@
import { isPrimitive, notNullish } from './helpers.js';
import { r as resolve } from './chunk-pathe.M-eThtNZ.js';
import './constants.js';
// src/vlq.ts
var comma = ",".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function decodeInteger(reader, relative) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = reader.next();
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -2147483648 | -value;
}
return relative + value;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max) return false;
return reader.peek() !== comma;
}
var StringReader = class {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
// src/sourcemap-codec.ts
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(";");
const line = [];
let sorted = true;
let lastCol = 0;
genColumn = 0;
while (reader.pos < semi) {
let seg;
genColumn = decodeInteger(reader, genColumn);
if (genColumn < lastCol) sorted = false;
lastCol = genColumn;
if (hasMoreVlq(reader, semi)) {
sourcesIndex = decodeInteger(reader, sourcesIndex);
sourceLine = decodeInteger(reader, sourceLine);
sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(reader, semi)) {
namesIndex = decodeInteger(reader, namesIndex);
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
} else {
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
}
} else {
seg = [genColumn];
}
line.push(seg);
reader.pos++;
}
if (!sorted) sort(line);
decoded.push(line);
reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[0] - b[0];
}
// src/trace-mapping.ts
// src/sourcemap-segment.ts
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
// src/binary-search.ts
var found = false;
function binarySearch(haystack, needle, low, high) {
while (low <= high) {
const mid = low + (high - low >> 1);
const cmp = haystack[mid][COLUMN] - needle;
if (cmp === 0) {
found = true;
return mid;
}
if (cmp < 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
found = false;
return low - 1;
}
function upperBound(haystack, needle, index) {
for (let i = index + 1; i < haystack.length; index = i++) {
if (haystack[i][COLUMN] !== needle) break;
}
return index;
}
function lowerBound(haystack, needle, index) {
for (let i = index - 1; i >= 0; index = i--) {
if (haystack[i][COLUMN] !== needle) break;
}
return index;
}
function memoizedBinarySearch(haystack, needle, state, key) {
const { lastKey, lastNeedle, lastIndex } = state;
let low = 0;
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
return lastIndex;
}
if (needle >= lastNeedle) {
low = lastIndex === -1 ? 0 : lastIndex;
} else {
high = lastIndex;
}
}
state.lastKey = key;
state.lastNeedle = needle;
return state.lastIndex = binarySearch(haystack, needle, low, high);
}
// src/trace-mapping.ts
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
function cast(map) {
return map;
}
function decodedMappings(map) {
var _a;
return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
}
function originalPositionFor(map, needle) {
let { line, column, bias } = needle;
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const decoded = decodedMappings(map);
if (line >= decoded.length) return OMapping(null, null, null, null);
const segments = decoded[line];
const index = traceSegmentInternal(
segments,
cast(map)._decodedMemo,
line,
column,
bias || GREATEST_LOWER_BOUND
);
if (index === -1) return OMapping(null, null, null, null);
const segment = segments[index];
if (segment.length === 1) return OMapping(null, null, null, null);
const { names, resolvedSources } = map;
return OMapping(
resolvedSources[segment[SOURCES_INDEX]],
segment[SOURCE_LINE] + 1,
segment[SOURCE_COLUMN],
segment.length === 5 ? names[segment[NAMES_INDEX]] : null
);
}
function OMapping(source, line, column, name) {
return { source, line, column, name };
}
function traceSegmentInternal(segments, memo, line, column, bias) {
let index = memoizedBinarySearch(segments, column, memo, line);
if (found) {
index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
} else if (bias === LEAST_UPPER_BOUND) index++;
if (index === -1 || index === segments.length) return -1;
return index;
}
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
const stackIgnorePatterns = [
"node:internal",
/\/packages\/\w+\/dist\//,
/\/@vitest\/\w+\/dist\//,
"/vitest/dist/",
"/vitest/src/",
"/node_modules/chai/",
"/node_modules/tinyspy/",
"/vite/dist/node/module-runner",
"/rolldown-vite/dist/node/module-runner",
"/deps/chunk-",
"/deps/@vitest",
"/deps/loupe",
"/deps/chai",
"/browser-playwright/dist/locators.js",
"/browser-webdriverio/dist/locators.js",
"/browser-preview/dist/locators.js",
/node:\w+/,
/__vitest_test__/,
/__vitest_browser__/,
"/@id/__x00__vitest/browser",
/\/deps\/vitest_/
];
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (!urlLike.includes(":")) {
return [urlLike];
}
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
if (!parts) {
return [urlLike];
}
let url = parts[1];
if (url.startsWith("async ")) {
url = url.slice(6);
}
if (url.startsWith("http:") || url.startsWith("https:")) {
const urlObj = new URL(url);
urlObj.searchParams.delete("import");
urlObj.searchParams.delete("browserv");
url = urlObj.pathname + urlObj.hash + urlObj.search;
}
if (url.startsWith("/@fs/")) {
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows ? 5 : 4);
}
if (url.includes("vitest=")) {
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
}
return [
url,
parts[2] || undefined,
parts[3] || undefined
];
}
function parseSingleFFOrSafariStack(raw) {
let line = raw.trim();
if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
return null;
}
if (line.includes(" > eval")) {
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
}
// Early return for lines that don't look like Firefox/Safari stack traces
// Firefox/Safari stack traces must contain '@' and should have location info after it
if (!line.includes("@")) {
return null;
}
// Find the correct @ that separates function name from location
// For cases like '@https://@fs/path' or 'functionName@https://@fs/path'
// we need to find the first @ that precedes a valid location (containing :)
let atIndex = -1;
let locationPart = "";
let functionName;
// Try each @ from left to right to find the one that gives us a valid location
for (let i = 0; i < line.length; i++) {
if (line[i] === "@") {
const candidateLocation = line.slice(i + 1);
// Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1")
if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
atIndex = i;
locationPart = candidateLocation;
functionName = i > 0 ? line.slice(0, i) : undefined;
break;
}
}
}
// Validate we found a valid location with minimum length (filename:line format)
if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
return null;
}
const [url, lineNumber, columnNumber] = extractLocation(locationPart);
if (!url || !lineNumber || !columnNumber) {
return null;
}
return {
file: url,
method: functionName || "",
line: Number.parseInt(lineNumber),
column: Number.parseInt(columnNumber)
};
}
function parseSingleStack(raw) {
const line = raw.trim();
if (!CHROME_IE_STACK_REGEXP.test(line)) {
return parseSingleFFOrSafariStack(line);
}
return parseSingleV8Stack(line);
}
// Based on https://github.com/stacktracejs/error-stack-parser
// Credit to stacktracejs
function parseSingleV8Stack(raw) {
let line = raw.trim();
if (!CHROME_IE_STACK_REGEXP.test(line)) {
return null;
}
if (line.includes("(eval ")) {
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
}
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
// capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in
// case it has spaces in it, as the string is split on \s+ later on
const location = sanitizedLine.match(/ (\(.+\)$)/);
// remove the parenthesized location from the line, if it was matched
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
// because this line doesn't have function name
const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
let method = location && sanitizedLine || "";
let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url;
if (!file || !lineNumber || !columnNumber) {
return null;
}
if (method.startsWith("async ")) {
method = method.slice(6);
}
if (file.startsWith("file://")) {
file = file.slice(7);
}
// normalize Windows path (\ -> /)
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
if (method) {
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
}
return {
method,
file,
line: Number.parseInt(lineNumber),
column: Number.parseInt(columnNumber)
};
}
function createStackString(stacks) {
return stacks.map((stack) => {
const line = `${stack.file}:${stack.line}:${stack.column}`;
if (stack.method) {
return ` at ${stack.method}(${line})`;
}
return ` at ${line}`;
}).join("\n");
}
function parseStacktrace(stack, options = {}) {
const { ignoreStackEntries = stackIgnorePatterns } = options;
let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
// remove vi.defineHelper's internal stacks
const helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__"));
if (helperIndex >= 0) {
stacks = stacks.slice(helperIndex + 1);
}
return stacks.map((stack) => {
if (options.getUrlId) {
stack.file = options.getUrlId(stack.file);
}
const map = options.getSourceMap?.(stack.file);
if (!map || typeof map !== "object" || !map.version) {
return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
}
const traceMap = new DecodedMap(map, stack.file);
const position = getOriginalPosition(traceMap, stack);
if (!position) {
return stack;
}
const { line, column, source, name } = position;
let file = source || stack.file;
if (file.match(/\/\w:\//)) {
file = file.slice(1);
}
if (shouldFilter(ignoreStackEntries, file)) {
return null;
}
if (line != null && column != null) {
return {
line,
column,
file,
method: name || stack.method
};
}
return stack;
}).filter((s) => s != null);
}
function shouldFilter(ignoreStackEntries, file) {
return ignoreStackEntries.some((p) => file.match(p));
}
function parseFFOrSafariStackTrace(stack) {
return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
}
function parseV8Stacktrace(stack) {
return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
}
function parseErrorStacktrace(e, options = {}) {
if (!e || isPrimitive(e)) {
return [];
}
if ("stacks" in e && e.stacks) {
return e.stacks;
}
const stackStr = e.stack || "";
// if "stack" property was overwritten at runtime to be something else,
// ignore the value because we don't know how to process it
let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : [];
if (!stackFrames.length) {
const e_ = e;
if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) {
stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options);
}
if (e_.sourceURL != null && e_.line != null && e_._column != null) {
stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options);
}
}
if (options.frameFilter) {
stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false);
}
e.stacks = stackFrames;
return stackFrames;
}
class DecodedMap {
_encoded;
_decoded;
_decodedMemo;
url;
version;
names = [];
resolvedSources;
constructor(map, from) {
this.map = map;
const { mappings, names, sources } = map;
this.version = map.version;
this.names = names || [];
this._encoded = mappings || "";
this._decodedMemo = memoizedState();
this.url = from;
this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || ""));
}
}
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function getOriginalPosition(map, needle) {
const result = originalPositionFor(map, needle);
if (result.column == null) {
return null;
}
return result;
}
export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace };