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,45 @@
import LazyResult from './lazy-result.js'
import { SourceMap } from './postcss.js'
import Processor from './processor.js'
import Result, { Message, ResultOptions } from './result.js'
import Root from './root.js'
import Warning from './warning.js'
declare namespace NoWorkResult {
export { NoWorkResult_ as default }
}
/**
* A Promise proxy for the result of PostCSS transformations.
* This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root`
* are accessed. See the example below for details.
* A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined.
*
* ```js
* const noWorkResult = postcss().process(css) // No plugins are defined.
* // CSS is not parsed
* let root = noWorkResult.root // now css is parsed because we accessed the root
* ```
*/
declare class NoWorkResult_ implements LazyResult<Root> {
catch: Promise<Result<Root>>['catch']
finally: Promise<Result<Root>>['finally']
then: Promise<Result<Root>>['then']
get content(): string
get css(): string
get map(): SourceMap
get messages(): Message[]
get opts(): ResultOptions
get processor(): Processor
get root(): Root
get [Symbol.toStringTag](): string
constructor(processor: Processor, css: string, opts: ResultOptions)
async(): Promise<Result<Root>>
sync(): Result<Root>
toString(): string
warnings(): Warning[]
}
declare class NoWorkResult extends NoWorkResult_ {}
export = NoWorkResult

View File

@@ -0,0 +1,11 @@
import * as ts from 'typescript';
import type { ParseSettings } from '../parseSettings';
import type { ASTAndDefiniteProgram } from './shared';
export declare function useProvidedPrograms(programInstances: Iterable<ts.Program>, parseSettings: ParseSettings): ASTAndDefiniteProgram;
/**
* Utility offered by parser to help consumers construct their own program instance.
*
* @param configFile the path to the tsconfig.json file, relative to `projectDirectory`
* @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()`
*/
export declare function createProgramFromConfigFile(configFile: string, projectDirectory?: string): ts.Program;

View File

@@ -0,0 +1,118 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "znaków", verb: "mieć" },
file: { unit: "bajtów", verb: "mieć" },
array: { unit: "elementów", verb: "mieć" },
set: { unit: "elementów", verb: "mieć" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "wyrażenie",
email: "adres email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data i godzina w formacie ISO",
date: "data w formacie ISO",
time: "godzina w formacie ISO",
duration: "czas trwania ISO",
ipv4: "adres IPv4",
ipv6: "adres IPv6",
cidrv4: "zakres IPv4",
cidrv6: "zakres IPv6",
base64: "ciąg znaków zakodowany w formacie base64",
base64url: "ciąg znaków zakodowany w formacie base64url",
json_string: "ciąg znaków w formacie JSON",
e164: "liczba E.164",
jwt: "JWT",
template_literal: "wejście",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "liczba",
array: "tablica",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue.expected}, otrzymano ${received}`;
}
return `Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Nieprawidłowe dane wejściowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`;
return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`;
}
return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`;
}
return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with")
return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;
if (_issue.format === "ends_with") return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;
if (_issue.format === "includes") return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;
if (_issue.format === "regex") return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;
return `Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`;
case "unrecognized_keys":
return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Nieprawidłowy klucz w ${issue.origin}`;
case "invalid_union":
return "Nieprawidłowe dane wejściowe";
case "invalid_element":
return `Nieprawidłowa wartość w ${issue.origin}`;
default:
return `Nieprawidłowe dane wejściowe`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_ts_add_disposable_resource.cjs",
"module": "../../esm/_ts_add_disposable_resource.js"
}

View File

@@ -0,0 +1,164 @@
# tslib
This is a runtime library for [TypeScript](https://www.typescriptlang.org/) that contains all of the TypeScript helper functions.
This library is primarily used by the `--importHelpers` flag in TypeScript.
When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file:
```ts
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
exports.x = {};
exports.y = __assign({}, exports.x);
```
will instead be emitted as something like the following:
```ts
var tslib_1 = require("tslib");
exports.x = {};
exports.y = tslib_1.__assign({}, exports.x);
```
Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead.
For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`.
# Installing
For the latest stable version, run:
## npm
```sh
# TypeScript 3.9.2 or later
npm install tslib
# TypeScript 3.8.4 or earlier
npm install tslib@^1
# TypeScript 2.3.2 or earlier
npm install tslib@1.6.1
```
## yarn
```sh
# TypeScript 3.9.2 or later
yarn add tslib
# TypeScript 3.8.4 or earlier
yarn add tslib@^1
# TypeScript 2.3.2 or earlier
yarn add tslib@1.6.1
```
## bower
```sh
# TypeScript 3.9.2 or later
bower install tslib
# TypeScript 3.8.4 or earlier
bower install tslib@^1
# TypeScript 2.3.2 or earlier
bower install tslib@1.6.1
```
## JSPM
```sh
# TypeScript 3.9.2 or later
jspm install tslib
# TypeScript 3.8.4 or earlier
jspm install tslib@^1
# TypeScript 2.3.2 or earlier
jspm install tslib@1.6.1
```
# Usage
Set the `importHelpers` compiler option on the command line:
```
tsc --importHelpers file.ts
```
or in your tsconfig.json:
```json
{
"compilerOptions": {
"importHelpers": true
}
}
```
#### For bower and JSPM users
You will need to add a `paths` mapping for `tslib`, e.g. For Bower users:
```json
{
"compilerOptions": {
"module": "amd",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["bower_components/tslib/tslib.d.ts"]
}
}
}
```
For JSPM users:
```json
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/tslib@2.x.y/tslib.d.ts"]
}
}
}
```
## Deployment
- Choose your new version number
- Set it in `package.json` and `bower.json`
- Create a tag: `git tag [version]`
- Push the tag: `git push --tags`
- Create a [release in GitHub](https://github.com/microsoft/tslib/releases)
- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow
Done.
# Contribute
There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript).
* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
# Documentation
* [Quick tutorial](http://www.typescriptlang.org/Tutorial)
* [Programming handbook](http://www.typescriptlang.org/Handbook)
* [Homepage](http://www.typescriptlang.org/)

View File

@@ -0,0 +1,212 @@
/**
* @fileoverview enforce `for` loop update clause moving the counter in the right direction.(for-direction)
* @author Aladdin-ADD<hh_2013@foxmail.com>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { getStaticValue } = require("@eslint-community/eslint-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Enforce `for` loop update clause moving the counter in the right direction",
recommended: true,
url: "https://eslint.org/docs/latest/rules/for-direction",
},
fixable: null,
schema: [],
messages: {
incorrectDirection:
"The update clause in this loop moves the variable in the wrong direction.",
},
},
create(context) {
const { sourceCode } = context;
/**
* report an error.
* @param {ASTNode} node the node to report.
* @returns {void}
*/
function report(node) {
context.report({
loc: {
start: node.loc.start,
end: sourceCode.getTokenBefore(node.body).loc.end,
},
messageId: "incorrectDirection",
});
}
/**
* check the right side of the assignment
* @param {ASTNode} update UpdateExpression to check
* @param {number} dir expected direction that could either be turned around or invalidated
* @returns {number} return dir, the negated dir, or zero if the counter does not change or the direction is not clear
*/
function getRightDirection(update, dir) {
const staticValue = getStaticValue(
update.right,
sourceCode.getScope(update),
);
if (
staticValue &&
["bigint", "boolean", "number"].includes(
typeof staticValue.value,
)
) {
const sign = Math.sign(Number(staticValue.value)) || 0; // convert NaN to 0
return dir * sign;
}
return 0;
}
/**
* check UpdateExpression add/sub the counter
* @param {ASTNode} update UpdateExpression to check
* @param {string} counter variable name to check
* @returns {number} if add return 1, if sub return -1, if nochange, return 0
*/
function getUpdateDirection(update, counter) {
if (
update.argument.type === "Identifier" &&
update.argument.name === counter
) {
if (update.operator === "++") {
return 1;
}
if (update.operator === "--") {
return -1;
}
}
return 0;
}
/**
* check AssignmentExpression add/sub the counter
* @param {ASTNode} update AssignmentExpression to check
* @param {string} counter variable name to check
* @returns {number} if add return 1, if sub return -1, if nochange, return 0
*/
function getAssignmentDirection(update, counter) {
if (update.left.name === counter) {
if (update.operator === "+=") {
return getRightDirection(update, 1);
}
if (update.operator === "-=") {
return getRightDirection(update, -1);
}
}
return 0;
}
/**
* Collects all expressions that modify the counter.
* @param {ASTNode} node The expression node to check.
* @param {string} counter The name of the counter variable.
* @returns {ASTNode[]} An array of modifying expressions.
*/
function getModifyingExpressions(node, counter) {
if (node.type === "SequenceExpression") {
return node.expressions.flatMap(expr =>
getModifyingExpressions(expr, counter),
);
}
if (
node.type === "UpdateExpression" &&
node.argument.type === "Identifier" &&
node.argument.name === counter
) {
return [node];
}
if (
node.type === "AssignmentExpression" &&
node.left.type === "Identifier" &&
node.left.name === counter
) {
return [node];
}
return [];
}
/**
* Determines the direction of a single update expression for the counter.
* @param {ASTNode} expr An expression node to check (UpdateExpression or AssignmentExpression).
* @param {string} counter The variable name of the counter.
* @returns {number} 1 if incrementing, -1 if decrementing, 0 if unknown or not modifying the counter.
*/
function getDirectionFromExpression(expr, counter) {
if (expr.type === "UpdateExpression") {
return getUpdateDirection(expr, counter);
}
if (expr.type === "AssignmentExpression") {
return getAssignmentDirection(expr, counter);
}
return 0;
}
return {
ForStatement(node) {
if (
node.test &&
node.test.type === "BinaryExpression" &&
node.update
) {
for (const counterPosition of ["left", "right"]) {
if (node.test[counterPosition].type !== "Identifier") {
continue;
}
const counter = node.test[counterPosition].name;
const operator = node.test.operator;
const update = node.update;
let wrongDirection;
if (operator === "<" || operator === "<=") {
wrongDirection =
counterPosition === "left" ? -1 : 1;
} else if (operator === ">" || operator === ">=") {
wrongDirection =
counterPosition === "left" ? 1 : -1;
} else {
return;
}
const mutatingExpressions = getModifyingExpressions(
update,
counter,
);
if (
mutatingExpressions.length === 1 &&
getDirectionFromExpression(
mutatingExpressions[0],
counter,
) === wrongDirection
) {
report(node);
}
}
}
},
};
},
};

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_possible_constructor_return.js";

View File

@@ -0,0 +1,203 @@
import { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
anum(value);
anum(length);
if (value < 0 || value >= 1 << (8 * length))
throw new Error('invalid I2OSP input: ' + value);
const res = Array.from({ length }).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 0xff;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function anum(item) {
if (!Number.isSafeInteger(item))
throw new Error('number expected');
}
function normDST(DST) {
if (!isBytes(DST) && typeof DST !== 'string')
throw new Error('DST must be Uint8Array or string');
return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
* Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
* [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
*/
export function expand_message_xmd(msg, DST, lenInBytes, H) {
abytes(msg);
anum(lenInBytes);
DST = normDST(DST);
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
if (DST.length > 255)
DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (lenInBytes > 65535 || ell > 255)
throw new Error('expand_message_xmd: invalid lenInBytes');
const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
const b = new Array(ell);
const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H(concatBytes(...args));
}
const pseudo_random_bytes = concatBytes(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
* 1. The collision resistance of H MUST be at least k bits.
* 2. H MUST be an XOF that has been proved indifferentiable from
* a random oracle under a reasonable cryptographic assumption.
* [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
*/
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
abytes(msg);
anum(lenInBytes);
DST = normDST(DST);
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
// DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
if (DST.length > 255) {
const dkLen = Math.ceil((2 * k) / 8);
DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error('expand_message_xof: invalid lenInBytes');
return (H.create({ dkLen: lenInBytes })
.update(msg)
.update(i2osp(lenInBytes, 2))
// 2. DST_prime = DST || I2OSP(len(DST), 1)
.update(DST)
.update(i2osp(DST.length, 1))
.digest());
}
/**
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
* [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
* @param msg a byte string containing the message to hash
* @param count the number of elements of F to output
* @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
* @returns [u_0, ..., u_(count - 1)], a list of field elements.
*/
export function hash_to_field(msg, count, options) {
_validateObject(options, {
p: 'bigint',
m: 'number',
k: 'number',
hash: 'function',
});
const { p, k, m, hash, expand, DST } = options;
if (!isHash(options.hash))
throw new Error('expected valid hash');
abytes(msg);
anum(count);
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
const len_in_bytes = count * m * L;
let prb; // pseudo_random_bytes
if (expand === 'xmd') {
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
}
else if (expand === 'xof') {
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
}
else if (expand === '_internal_pass') {
// for internal tests only
prb = msg;
}
else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = mod(os2ip(tv), p);
}
u[i] = e;
}
return u;
}
export function isogenyMap(field, map) {
// Make same order as in spec
const coeff = map.map((i) => Array.from(i).reverse());
return (x, y) => {
const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
// 6.6.3
// Exceptional cases of iso_map are inputs that cause the denominator of
// either rational function to evaluate to zero; such cases MUST return
// the identity point on E.
const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
x = field.mul(xn, xd_inv); // xNum / xDen
y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
return { x, y };
};
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
if (typeof mapToCurve !== 'function')
throw new Error('mapToCurve() must be defined');
function map(num) {
return Point.fromAffine(mapToCurve(num));
}
function clear(initial) {
const P = initial.clearCofactor();
if (P.equals(Point.ZERO))
return Point.ZERO; // zero will throw in assert
P.assertValidity();
return P;
}
return {
defaults,
hashToCurve(msg, options) {
const opts = Object.assign({}, defaults, options);
const u = hash_to_field(msg, 2, opts);
const u0 = map(u[0]);
const u1 = map(u[1]);
return clear(u0.add(u1));
},
encodeToCurve(msg, options) {
const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
const opts = Object.assign({}, defaults, optsDst, options);
const u = hash_to_field(msg, 1, opts);
const u0 = map(u[0]);
return clear(u0);
},
/** See {@link H2CHasher} */
mapToCurve(scalars) {
if (!Array.isArray(scalars))
throw new Error('expected array of bigints');
for (const i of scalars)
if (typeof i !== 'bigint')
throw new Error('expected array of bigints');
return clear(map(scalars));
},
// hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
// RFC 9380, draft-irtf-cfrg-bbs-signatures-08
hashToScalar(msg, options) {
// @ts-ignore
const N = Point.Fn.ORDER;
const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
return hash_to_field(msg, 1, opts)[0][0];
},
};
}
//# sourceMappingURL=hash-to-curve.js.map

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2025_float16: LibDefinition;

View File

@@ -0,0 +1,10 @@
import { a as Debugger, i as DebugOptions, n as enabled, o as Formatters, r as namespaces, s as InspectOptions, t as disable } from "./core.js";
//#region src/browser.d.ts
declare function createDebug(namespace: string, options?: DebugOptions): Debugger;
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*/
declare function enable(namespaces: string): void;
//#endregion
export { type DebugOptions, type Debugger, type Formatters, type InspectOptions, createDebug, disable, enable, enabled, namespaces };

View File

@@ -0,0 +1,74 @@
/**
* @fileoverview Types for object-schema package.
*/
/**
* Built-in validation strategies.
*/
export type BuiltInValidationStrategy = "array" | "boolean" | "number" | "object" | "object?" | "string" | "string!";
/**
* Built-in merge strategies.
*/
export type BuiltInMergeStrategy = "assign" | "overwrite" | "replace";
/**
* Custom merge strategy.
*/
export type CustomMergeStrategy = (target: any, source: any) => any;
/**
* Custom validation strategy.
*/
export type CustomValidationStrategy = (value: any) => void;
interface BasePropertyDefinition {
/**
* Indicates if the property is required.
*/
required?: boolean;
/**
* The other properties that must be present when this property is used.
*/
requires?: string[];
}
/**
* Property definition that specifies explicit merge and validation strategies.
* This form cannot include a `schema`.
*/
export interface PropertyDefinitionWithStrategies extends BasePropertyDefinition {
/**
* The schema for the object value of this property.
*/
schema?: never;
/**
* The strategy to merge the property.
*/
merge: BuiltInMergeStrategy | CustomMergeStrategy;
/**
* The strategy to validate the property.
*/
validate: BuiltInValidationStrategy | CustomValidationStrategy;
}
/**
* Property definition that uses a nested `schema`.
* When `schema` is present, merge and validation strategies are optional.
*/
export interface PropertyDefinitionWithSchema extends BasePropertyDefinition {
/**
* The schema for the object value of this property.
*/
schema: ObjectDefinition;
/**
* The strategy to merge the property.
*/
merge?: BuiltInMergeStrategy | CustomMergeStrategy;
/**
* The strategy to validate the property.
*/
validate?: BuiltInValidationStrategy | CustomValidationStrategy;
}
/**
* Property definition.
*/
export type PropertyDefinition = PropertyDefinitionWithStrategies | PropertyDefinitionWithSchema;
/**
* Object definition.
*/
export type ObjectDefinition = Record<string, PropertyDefinition>;
export {};

View File

@@ -0,0 +1,96 @@
/**
* @fileoverview Rule to flag when using new Function
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const callMethods = new Set(["apply", "bind", "call"]);
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow `new` operators with the `Function` object",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-new-func",
},
schema: [],
messages: {
noFunctionConstructor: "The Function constructor is eval.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
"Program:exit"(node) {
const globalScope = sourceCode.getScope(node);
const variable = globalScope.set.get("Function");
if (variable && variable.defs.length === 0) {
variable.references.forEach(ref => {
const idNode = ref.identifier;
const { parent } = idNode;
let evalNode;
if (parent) {
if (
idNode === parent.callee &&
(parent.type === "NewExpression" ||
parent.type === "CallExpression")
) {
evalNode = parent;
} else if (
parent.type === "MemberExpression" &&
idNode === parent.object &&
callMethods.has(
astUtils.getStaticPropertyName(parent),
)
) {
const maybeCallee =
parent.parent.type === "ChainExpression"
? parent.parent
: parent;
if (
maybeCallee.parent.type ===
"CallExpression" &&
maybeCallee.parent.callee === maybeCallee
) {
evalNode = maybeCallee.parent;
}
}
}
if (evalNode) {
context.report({
node: evalNode,
messageId: "noFunctionConstructor",
});
}
});
}
},
};
},
};

View File

@@ -0,0 +1,36 @@
"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 __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("./BlockScope"), exports);
__exportStar(require("./CatchScope"), exports);
__exportStar(require("./ClassFieldInitializerScope"), exports);
__exportStar(require("./ClassScope"), exports);
__exportStar(require("./ClassStaticBlockScope"), exports);
__exportStar(require("./ConditionalTypeScope"), exports);
__exportStar(require("./ForScope"), exports);
__exportStar(require("./FunctionExpressionNameScope"), exports);
__exportStar(require("./FunctionScope"), exports);
__exportStar(require("./FunctionTypeScope"), exports);
__exportStar(require("./GlobalScope"), exports);
__exportStar(require("./MappedTypeScope"), exports);
__exportStar(require("./ModuleScope"), exports);
__exportStar(require("./Scope"), exports);
__exportStar(require("./ScopeType"), exports);
__exportStar(require("./SwitchScope"), exports);
__exportStar(require("./TSEnumScope"), exports);
__exportStar(require("./TSModuleScope"), exports);
__exportStar(require("./TypeScope"), exports);
__exportStar(require("./WithScope"), exports);

View File

@@ -0,0 +1,123 @@
import { V as Vitest, av as ResolvedCoverageOptions, a$ as CoverageMap, ao as ReportContext, T as TestProject } from './chunks/reporters.d.DtoKVV2s.js';
import { TransformResult } from 'vite';
import { a as AfterSuiteRunMeta } from './chunks/traces.d.D2T_R8rx.js';
import '@vitest/runner';
import '@vitest/utils';
import 'node:stream';
import './chunks/config.d.A1h_Y6Jt.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/browser.d.BcoexmFG.js';
import './chunks/worker.d.ZpHpO4yb.js';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
import './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/expect';
import 'vitest/optional-types.js';
import './chunks/benchmark.d.DAaHLpsq.js';
import '@vitest/runner/utils';
import 'tinybench';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/coverage.d.BZtK59WP.js';
import '@vitest/snapshot/manager';
import 'node:console';
import 'node:fs';
type Threshold = "lines" | "functions" | "statements" | "branches";
interface ResolvedThreshold {
coverageMap: CoverageMap;
name: string;
thresholds: Partial<Record<Threshold, number | undefined>>;
}
/**
* Holds info about raw coverage results that are stored on file system:
*
* ```json
* "project-a": {
* "web": {
* "tests/math.test.ts": "coverage-1.json",
* "tests/utils.test.ts": "coverage-2.json",
* // ^^^^^^^^^^^^^^^ Raw coverage on file system
* },
* "ssr": { ... },
* "browser": { ... },
* },
* "project-b": ...
* ```
*/
type CoverageFiles = Map<NonNullable<AfterSuiteRunMeta["projectName"]> | symbol, Record<AfterSuiteRunMeta["environment"], {
[TestFilenames: string]: string;
}>>;
declare class BaseCoverageProvider {
ctx: Vitest;
readonly name: "v8" | "istanbul";
version: string;
options: ResolvedCoverageOptions;
globCache: Map<string, boolean>;
autoUpdateMarker: string;
coverageFiles: CoverageFiles;
pendingPromises: Promise<void>[];
coverageFilesDirectory: string;
roots: string[];
changedFiles?: string[];
_initialize(ctx: Vitest): void;
/**
* Check if file matches `coverage.include` but not `coverage.exclude`
*/
isIncluded(_filename: string, root?: string): boolean;
private getUntestedFilesByRoot;
getUntestedFiles(testedFiles: string[]): Promise<string[]>;
createCoverageMap(): CoverageMap;
generateReports(_: CoverageMap, __: boolean | undefined): Promise<void>;
parseConfigModule(_: string): Promise<{
generate: () => {
code: string;
};
}>;
resolveOptions(): ResolvedCoverageOptions;
clean(clean?: boolean): Promise<void>;
private normalizeCoverageFileError;
onAfterSuiteRun({ coverage, environment, projectName, testFiles }: AfterSuiteRunMeta): void;
readCoverageFiles<CoverageType>({ onFileRead, onFinished, onDebug }: {
/** Callback invoked with a single coverage result */
onFileRead: (data: CoverageType) => void;
/** Callback invoked once all results of a project for specific transform mode are read */
onFinished: (project: Vitest["projects"][number], environment: string) => Promise<void>;
onDebug: ((...logs: any[]) => void) & {
enabled: boolean;
};
}): Promise<void>;
cleanAfterRun(): Promise<void>;
onTestRunStart(): Promise<void>;
onTestFailure(): Promise<void>;
reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext): Promise<void>;
reportThresholds(coverageMap: CoverageMap, allTestsRun: boolean | undefined): Promise<void>;
/**
* Constructs collected coverage and users' threshold options into separate sets
* where each threshold set holds their own coverage maps. Threshold set is either
* for specific files defined by glob pattern or global for all other files.
*/
private resolveThresholds;
/**
* Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
*/
private checkThresholds;
/**
* Check if current coverage is above configured thresholds and bump the thresholds if needed
*/
updateThresholds({ thresholds: allThresholds, onUpdate, configurationFile }: {
thresholds: ResolvedThreshold[];
configurationFile: unknown;
onUpdate: () => void;
}): Promise<void>;
mergeReports(coverageMaps: unknown[]): Promise<void>;
hasTerminalReporter(reporters: ResolvedCoverageOptions["reporter"]): boolean;
toSlices<T>(array: T[], size: number): T[][];
transformFile(url: string, project: TestProject, viteEnvironment: string): Promise<TransformResult | null | undefined>;
createUncoveredFileTransformer(ctx: Vitest): (filename: string) => Promise<TransformResult | null | undefined>;
}
export { BaseCoverageProvider };

View File

@@ -0,0 +1,683 @@
import { IncomingMessage, ServerResponse } from 'http'
import { mock } from 'node:test'
import { Socket } from 'net'
import { expectError, expectType } from 'tsd'
import pino, { LogFn, LoggerOptions } from '../../'
import Logger = pino.Logger
const log = pino()
const info = log.info
const error = log.error
info('hello world')
error('this is at error level')
// primitive types
info('simple string')
info(true)
info(42)
info(3.14)
info(null)
info(undefined)
// object types
info({ a: 1, b: '2' })
info(new Error())
info(new Date())
info([])
info(new Map())
info(new Set())
// placeholder messages
info('Hello %s', 'world')
info('The answer is %d', 42)
info('The object is %o', { a: 1, b: '2' })
info('The json is %j', { a: 1, b: '2' })
info('The object is %O', { a: 1, b: '2' })
info('The answer is %d and the question is %s with %o', 42, 'unknown', {
correct: 'order',
})
info('Missing placeholder is fine %s')
// %s placeholder supports all primitive types
info('Boolean %s', true)
info('Boolean %s', false)
info('Number %s', 123)
info('Number %s', 3.14)
info('BigInt %s', BigInt(123))
info('Null %s', null)
info('Undefined %s', undefined)
info('Symbol %s', Symbol('test'))
info('String %s', 'hello')
// %s placeholder with multiple primitives
info('Multiple primitives %s %s %s', true, 42, 'world')
info(
'All primitive types %s %s %s %s %s %s %s',
'string',
123,
true,
BigInt(123),
null,
undefined,
Symbol('test')
)
declare const errorOrString: string | Error
info(errorOrString)
// %o placeholder supports primitives too (except undefined)
info('Boolean %o', true)
info('Boolean %o', false)
info('Number %o', 123)
info('Number %o', 3.14)
info('BigInt %o', BigInt(123))
info('Null %o', null)
info('Symbol %o', Symbol('test'))
info('String %o', 'hello')
// placeholder messages type errors
expectError(info('The answer is %d', 'not a number'))
expectError(
info(
'The answer is %d and the question is %s with %o',
'unknown',
{ incorrect: 'order' },
42
)
)
expectError(info('Extra message %s', 'after placeholder', 'not allowed'))
// object types with messages
info({ obj: 42 }, 'hello world')
info({ obj: 42, b: 2 }, 'hello world')
info({ obj: { aa: 'bbb' } }, 'another')
info({ a: 1, b: '2' }, 'hello world with %s', 'extra data')
// Extra message after placeholder
expectError(info({ a: 1, b: '2' }, 'hello world with %d', 2, 'extra'))
// metadata with messages type passes, because of custom toString method
// We can't detect if the object has a custom toString method that returns a string
info({ a: 1, b: '2' }, 'hello world with %s', {})
// metadata after message
expectError(info('message', { a: 1, b: '2' }))
// multiple strings without placeholder
expectError(info('string1', 'string2'))
expectError(info('string1', 'string2', 'string3'))
setImmediate(info, 'after setImmediate')
error(new Error('an error'))
const writeSym = pino.symbols.writeSym
const testUniqSymbol = {
[pino.symbols.needsMetadataGsym]: true,
}[pino.symbols.needsMetadataGsym]
const log2: pino.Logger = pino({
name: 'myapp',
safe: true,
serializers: {
req: pino.stdSerializers.req,
res: pino.stdSerializers.res,
err: pino.stdSerializers.err,
},
})
pino({
write (o) {},
})
pino({
mixin () {
return { customName: 'unknown', customId: 111 }
},
})
pino({
mixin: () => ({ customName: 'unknown', customId: 111 }),
})
pino({
mixin: (context: object) => ({ customName: 'unknown', customId: 111 }),
})
pino({
mixin: (context: object, level: number) => ({
customName: 'unknown',
customId: 111,
}),
})
pino({
redact: { paths: [], censor: 'SECRET' },
})
pino({
redact: { paths: [], censor: () => 'SECRET' },
})
pino({
redact: { paths: [], censor: (value) => value },
})
pino({
redact: { paths: [], censor: (value, path) => path.join() },
})
pino({
redact: {
paths: [],
censor: (value): string => 'SECRET',
},
})
expectError(
pino({
redact: { paths: [], censor: (value: string) => value },
})
)
pino({
depthLimit: 1,
})
pino({
edgeLimit: 1,
})
pino({
browser: {
write (o) {},
},
})
pino({
browser: {
write: {
info (o) {},
error (o) {},
},
serialize: true,
asObject: true,
transmit: {
level: 'fatal',
send: (level, logEvent) => {
level
logEvent.bindings
logEvent.level
logEvent.ts
logEvent.messages
},
},
disabled: false,
},
})
pino({
browser: {
asObjectBindingsOnly: true,
},
})
pino({}, undefined)
pino({ base: null })
if ('pino' in log) console.log(`pino version: ${log.pino}`)
expectType<void>(log.flush())
log.flush((err?: Error) => undefined)
log.child({ a: 'property' }).info('hello child!')
log.level = 'error'
log.info('nope')
const child = log.child({ foo: 'bar' })
child.info('nope again')
child.level = 'info'
child.info('hooray')
log.info('nope nope nope')
log.child({ foo: 'bar' }, { level: 'debug' }).debug('debug!')
child.bindings()
const customSerializers = {
test () {
return 'this is my serializer'
},
}
pino()
.child({}, { serializers: customSerializers })
.info({ test: 'should not show up' })
const child2 = log.child({ father: true })
const childChild = child2.child({ baby: true })
const childRedacted = pino().child({}, { redact: ['path'] })
childRedacted.info({
msg: 'logged with redacted properties',
path: 'Not shown',
})
const childAnotherRedacted = pino().child(
{},
{
redact: {
paths: ['anotherPath'],
censor: 'Not the log you\re looking for',
},
}
)
childAnotherRedacted.info({
msg: 'another logged with redacted properties',
anotherPath: 'Not shown',
})
log.level = 'info'
if (log.levelVal === 30) {
console.log('logger level is `info`')
}
const listener = (lvl: any, val: any, prevLvl: any, prevVal: any) => {
console.log(lvl, val, prevLvl, prevVal)
}
log.on('level-change', (lvl, val, prevLvl, prevVal, logger) => {
console.log(lvl, val, prevLvl, prevVal)
})
log.level = 'trace'
log.removeListener('level-change', listener)
log.level = 'info'
pino.levels.values.error === 50
pino.levels.labels[50] === 'error'
const logstderr: pino.Logger = pino(process.stderr)
logstderr.error('on stderr instead of stdout')
log.useLevelLabels = true
log.info('lol')
log.level === 'info'
const isEnabled: boolean = log.isLevelEnabled('info')
const redacted = pino({
redact: ['path'],
})
redacted.info({
msg: 'logged with redacted properties',
path: 'Not shown',
})
const anotherRedacted = pino({
redact: {
paths: ['anotherPath'],
censor: 'Not the log you\re looking for',
},
})
anotherRedacted.info({
msg: 'another logged with redacted properties',
anotherPath: 'Not shown',
})
const withTimeFn = pino({
timestamp: pino.stdTimeFunctions.isoTime,
})
const withRFC3339TimeFn = pino({
timestamp: pino.stdTimeFunctions.isoTimeNano,
})
const withNestedKey = pino({
nestedKey: 'payload',
})
const withHooks = pino({
hooks: {
logMethod (args, method, level) {
expectType<pino.Logger>(this)
return method.apply(this, args)
},
streamWrite (s) {
expectType<string>(s)
return s.replaceAll('secret-key', 'xxx')
},
},
})
// Properties/types imported from pino-std-serializers
const wrappedErrSerializer = pino.stdSerializers.wrapErrorSerializer(
(err: pino.SerializedError) => {
return { ...err, newProp: 'foo' }
}
)
const wrappedReqSerializer = pino.stdSerializers.wrapRequestSerializer(
(req: pino.SerializedRequest) => {
return { ...req, newProp: 'foo' }
}
)
const wrappedResSerializer = pino.stdSerializers.wrapResponseSerializer(
(res: pino.SerializedResponse) => {
return { ...res, newProp: 'foo' }
}
)
const socket = new Socket()
const incomingMessage = new IncomingMessage(socket)
const serverResponse = new ServerResponse(incomingMessage)
const mappedHttpRequest: { req: pino.SerializedRequest } =
pino.stdSerializers.mapHttpRequest(incomingMessage)
const mappedHttpResponse: { res: pino.SerializedResponse } =
pino.stdSerializers.mapHttpResponse(serverResponse)
const serializedErr: pino.SerializedError = pino.stdSerializers.err(
new Error()
)
const serializedReq: pino.SerializedRequest =
pino.stdSerializers.req(incomingMessage)
const serializedRes: pino.SerializedResponse =
pino.stdSerializers.res(serverResponse)
/**
* Destination static method
*/
const destinationViaDefaultArgs = pino.destination()
const destinationViaStrFileDescriptor = pino.destination('/log/path')
const destinationViaNumFileDescriptor = pino.destination(2)
const destinationViaStream = pino.destination(process.stdout)
const destinationViaOptionsObject = pino.destination({
dest: '/log/path',
sync: false,
})
pino(destinationViaDefaultArgs)
pino({ name: 'my-logger' }, destinationViaDefaultArgs)
pino(destinationViaStrFileDescriptor)
pino({ name: 'my-logger' }, destinationViaStrFileDescriptor)
pino(destinationViaNumFileDescriptor)
pino({ name: 'my-logger' }, destinationViaNumFileDescriptor)
pino(destinationViaStream)
pino({ name: 'my-logger' }, destinationViaStream)
pino(destinationViaOptionsObject)
pino({ name: 'my-logger' }, destinationViaOptionsObject)
try {
throw new Error('Some error')
} catch (err) {
log.error(err)
}
interface StrictShape {
activity: string;
err?: unknown;
}
info<StrictShape>({
activity: 'Required property',
})
const logLine: pino.LogDescriptor = {
level: 20,
msg: 'A log message',
time: new Date().getTime(),
aCustomProperty: true,
}
interface CustomLogger extends pino.Logger {
customMethod(msg: string, ...args: unknown[]): void;
}
const serializerFunc: pino.SerializerFn = () => {}
const writeFunc: pino.WriteFn = () => {}
interface CustomBaseLogger extends pino.BaseLogger {
child(): CustomBaseLogger;
}
const customBaseLogger: CustomBaseLogger = {
level: 'info',
fatal () {},
error () {},
warn () {},
info () {},
debug () {},
trace () {},
silent () {},
child () {
return this
},
msgPrefix: 'prefix',
}
// custom levels
const log3 = pino({ customLevels: { myLevel: 100 } })
expectError(log3.log())
log3.level = 'myLevel'
log3.myLevel('')
log3.child({}).myLevel('')
log3.on('level-change', (lvl, val, prevLvl, prevVal, instance) => {
instance.myLevel('foo')
})
const clog3 = log3.child({}, { customLevels: { childLevel: 120 } })
// child inherit parent
clog3.myLevel('')
// child itself
clog3.childLevel('')
const cclog3 = clog3.child({}, { customLevels: { childLevel2: 130 } })
// child inherit root
cclog3.myLevel('')
// child inherit parent
cclog3.childLevel('')
// child itself
cclog3.childLevel2('')
const ccclog3 = clog3.child({})
expectError(ccclog3.nonLevel(''))
const withChildCallback = pino({
onChild: (child: Logger) => {},
})
withChildCallback.onChild = (child: Logger) => {}
pino({
crlf: true,
})
const customLevels = { foo: 99, bar: 42 }
const customLevelLogger = pino({ customLevels })
type CustomLevelLogger = typeof customLevelLogger
type CustomLevelLoggerLevels = pino.Level | keyof typeof customLevels
const fn = (logger: Pick<CustomLevelLogger, CustomLevelLoggerLevels>) => {}
const customLevelChildLogger = customLevelLogger.child({ name: 'child' })
fn(customLevelChildLogger) // missing foo typing
// unknown option
expectError(
pino({
hello: 'world',
})
)
// unknown option
expectError(
pino({
hello: 'world',
customLevels: {
log: 30,
},
})
)
function dangerous () {
throw Error('foo')
}
try {
dangerous()
} catch (err) {
log.error(err)
}
try {
dangerous()
} catch (err) {
log.error({ err })
}
const bLogger = pino({
customLevels: {
log: 5,
},
level: 'log',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
},
},
})
// Test that we can properly extract parameters from the log fn type
type LogParam = Parameters<LogFn>
const [param1, param2, param3, param4]: LogParam = [
{ multiple: 'params' },
'should',
'be',
'accepted',
]
expectType<unknown>(param1)
expectType<string>(param2)
expectType<unknown>(param3)
expectType<unknown>(param4)
const logger = mock.fn<LogFn>()
logger.mock.calls[0].arguments[1]?.includes('I should be able to get params')
const hooks: LoggerOptions['hooks'] = {
logMethod (this, parameters, method) {
if (parameters.length >= 2) {
const [parameter1, parameter2, ...remainingParameters] = parameters
if (typeof parameter1 === 'string') {
return method.apply(this, [
parameter2,
parameter1,
...remainingParameters,
])
}
return method.apply(this, [parameter2])
}
return method.apply(this, parameters)
},
}
expectType<Logger<'log'>>(
pino({
customLevels: {
log: 5,
},
level: 'log',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
},
},
})
)
const parentLogger1 = pino(
{
customLevels: { myLevel: 90 },
onChild: (child) => {
const a = child.myLevel
},
},
process.stdout
)
parentLogger1.onChild = (child) => {
child.myLevel('')
}
const childLogger1 = parentLogger1.child({})
childLogger1.myLevel('')
expectError(childLogger1.doesntExist(''))
const parentLogger2 = pino({}, process.stdin)
expectError(
(parentLogger2.onChild = (child) => {
const b = child.doesntExist
})
)
const childLogger2 = parentLogger2.child({})
expectError(childLogger2.doesntExist)
expectError(
pino(
{
onChild: (child) => {
const a = child.doesntExist
},
},
process.stdout
)
)
const pinoWithoutLevelsSorting = pino({})
const pinoWithDescSortingLevels = pino({ levelComparison: 'DESC' })
const pinoWithAscSortingLevels = pino({ levelComparison: 'ASC' })
const pinoWithCustomSortingLevels = pino({ levelComparison: () => false })
// with wrong level comparison direction
expectError(pino({ levelComparison: 'SOME' }), process.stdout)
// with wrong level comparison type
expectError(pino({ levelComparison: 123 }), process.stdout)
// with wrong custom level comparison return type
expectError(pino({ levelComparison: () => null }), process.stdout)
expectError(pino({ levelComparison: () => 1 }), process.stdout)
expectError(pino({ levelComparison: () => 'string' }), process.stdout)
const customLevelsOnlyOpts = {
useOnlyCustomLevels: true,
customLevels: {
customDebug: 10,
info: 20, // to make sure the default names are also available for override
customNetwork: 30,
customError: 40,
},
level: 'customDebug',
} satisfies LoggerOptions
const loggerWithCustomLevelOnly = pino(customLevelsOnlyOpts)
loggerWithCustomLevelOnly.customDebug('test3')
loggerWithCustomLevelOnly.info('test4')
loggerWithCustomLevelOnly.customError('test5')
loggerWithCustomLevelOnly.customNetwork('test6')
expectError(loggerWithCustomLevelOnly.fatal('test'))
expectError(loggerWithCustomLevelOnly.error('test'))
expectError(loggerWithCustomLevelOnly.warn('test'))
expectError(loggerWithCustomLevelOnly.debug('test'))
expectError(loggerWithCustomLevelOnly.trace('test'))
// Module extension
declare module '../../' {
interface LogFnFields {
bannedField?: never;
typeCheckedField?: string;
}
}
info({ typeCheckedField: 'bar' })
expectError(info({ bannedField: 'bar' }))
expectError(info({ typeCheckedField: 123 }))
const someGenericFunction = <T extends string | number | symbol = never>(
arg: Record<T, unknown>
) => {
info(arg)
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_sliced_to_array_loose.cjs",
"module": "../../esm/_sliced_to_array_loose.js"
}

View File

@@ -0,0 +1,2 @@
import * as ts from 'typescript';
export declare function typeDeclaredInPackageDeclarationFile(packageName: string, declarations: ts.Node[], declarationFiles: ts.SourceFile[], program: ts.Program): boolean;

View File

@@ -0,0 +1,59 @@
export interface URIComponents {
scheme?: string;
userinfo?: string;
host?: string;
port?: number | string;
path?: string;
query?: string;
fragment?: string;
reference?: string;
error?: string;
}
export interface URIOptions {
scheme?: string;
reference?: string;
tolerant?: boolean;
absolutePath?: boolean;
iri?: boolean;
unicodeSupport?: boolean;
domainHost?: boolean;
}
export interface URISchemeHandler<Components extends URIComponents = URIComponents, Options extends URIOptions = URIOptions, ParentComponents extends URIComponents = URIComponents> {
scheme: string;
parse(components: ParentComponents, options: Options): Components;
serialize(components: Components, options: Options): ParentComponents;
unicodeSupport?: boolean;
domainHost?: boolean;
absolutePath?: boolean;
}
export interface URIRegExps {
NOT_SCHEME: RegExp;
NOT_USERINFO: RegExp;
NOT_HOST: RegExp;
NOT_PATH: RegExp;
NOT_PATH_NOSCHEME: RegExp;
NOT_QUERY: RegExp;
NOT_FRAGMENT: RegExp;
ESCAPE: RegExp;
UNRESERVED: RegExp;
OTHER_CHARS: RegExp;
PCT_ENCODED: RegExp;
IPV4ADDRESS: RegExp;
IPV6ADDRESS: RegExp;
}
export declare const SCHEMES: {
[scheme: string]: URISchemeHandler;
};
export declare function pctEncChar(chr: string): string;
export declare function pctDecChars(str: string): string;
export declare function parse(uriString: string, options?: URIOptions): URIComponents;
export declare function removeDotSegments(input: string): string;
export declare function serialize(components: URIComponents, options?: URIOptions): string;
export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents;
export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string;
export declare function normalize(uri: string, options?: URIOptions): string;
export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents;
export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean;
export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean;
export declare function escapeComponent(str: string, options?: URIOptions): string;
export declare function unescapeComponent(str: string, options?: URIOptions): string;

View File

@@ -0,0 +1,67 @@
/**
* @fileoverview Rule to disallow use of new operator with the `require` function
* @author Wil Moore III
* @deprecated in ESLint v7.0.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Node.js rules were moved out of ESLint core.",
url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules",
deprecatedSince: "7.0.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"eslint-plugin-n now maintains deprecated Node.js-related rules.",
plugin: {
name: "eslint-plugin-n",
url: "https://github.com/eslint-community/eslint-plugin-n",
},
rule: {
name: "no-new-require",
url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-new-require.md",
},
},
],
},
type: "suggestion",
docs: {
description: "Disallow `new` operators with calls to `require`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-new-require",
},
schema: [],
messages: {
noNewRequire: "Unexpected use of new with require.",
},
},
create(context) {
return {
NewExpression(node) {
if (
node.callee.type === "Identifier" &&
node.callee.name === "require"
) {
context.report({
node,
messageId: "noNewRequire",
});
}
},
};
},
};

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.esnext_object = void 0;
const base_config_1 = require("./base-config");
exports.esnext_object = {
libs: [],
variables: [['ObjectConstructor', base_config_1.TYPE]],
};