WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,642 @@
|
||||
'use strict';
|
||||
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// See LICENSE.md for more information.
|
||||
|
||||
//
|
||||
// Utilities
|
||||
//
|
||||
|
||||
/**
|
||||
* @param {number} a The number to test.
|
||||
* @param {number} min The minimum value in the range, inclusive.
|
||||
* @param {number} max The maximum value in the range, inclusive.
|
||||
* @return {boolean} True if a >= min and a <= max.
|
||||
*/
|
||||
function inRange(a, min, max) {
|
||||
return min <= a && a <= max;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} o
|
||||
* @return {Object}
|
||||
*/
|
||||
function ToDictionary(o) {
|
||||
if (o === undefined) return {};
|
||||
if (o === Object(o)) return o;
|
||||
throw TypeError('Could not convert argument to dictionary');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} string Input string of UTF-16 code units.
|
||||
* @return {!Array.<number>} Code points.
|
||||
*/
|
||||
function stringToCodePoints(string) {
|
||||
// https://heycam.github.io/webidl/#dfn-obtain-unicode
|
||||
|
||||
// 1. Let S be the DOMString value.
|
||||
var s = String(string);
|
||||
|
||||
// 2. Let n be the length of S.
|
||||
var n = s.length;
|
||||
|
||||
// 3. Initialize i to 0.
|
||||
var i = 0;
|
||||
|
||||
// 4. Initialize U to be an empty sequence of Unicode characters.
|
||||
var u = [];
|
||||
|
||||
// 5. While i < n:
|
||||
while (i < n) {
|
||||
|
||||
// 1. Let c be the code unit in S at index i.
|
||||
var c = s.charCodeAt(i);
|
||||
|
||||
// 2. Depending on the value of c:
|
||||
|
||||
// c < 0xD800 or c > 0xDFFF
|
||||
if (c < 0xD800 || c > 0xDFFF) {
|
||||
// Append to U the Unicode character with code point c.
|
||||
u.push(c);
|
||||
}
|
||||
|
||||
// 0xDC00 ≤ c ≤ 0xDFFF
|
||||
else if (0xDC00 <= c && c <= 0xDFFF) {
|
||||
// Append to U a U+FFFD REPLACEMENT CHARACTER.
|
||||
u.push(0xFFFD);
|
||||
}
|
||||
|
||||
// 0xD800 ≤ c ≤ 0xDBFF
|
||||
else if (0xD800 <= c && c <= 0xDBFF) {
|
||||
// 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
|
||||
// CHARACTER.
|
||||
if (i === n - 1) {
|
||||
u.push(0xFFFD);
|
||||
}
|
||||
// 2. Otherwise, i < n−1:
|
||||
else {
|
||||
// 1. Let d be the code unit in S at index i+1.
|
||||
var d = string.charCodeAt(i + 1);
|
||||
|
||||
// 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
|
||||
if (0xDC00 <= d && d <= 0xDFFF) {
|
||||
// 1. Let a be c & 0x3FF.
|
||||
var a = c & 0x3FF;
|
||||
|
||||
// 2. Let b be d & 0x3FF.
|
||||
var b = d & 0x3FF;
|
||||
|
||||
// 3. Append to U the Unicode character with code point
|
||||
// 2^16+2^10*a+b.
|
||||
u.push(0x10000 + (a << 10) + b);
|
||||
|
||||
// 4. Set i to i+1.
|
||||
i += 1;
|
||||
}
|
||||
|
||||
// 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
|
||||
// U+FFFD REPLACEMENT CHARACTER.
|
||||
else {
|
||||
u.push(0xFFFD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Set i to i+1.
|
||||
i += 1;
|
||||
}
|
||||
|
||||
// 6. Return U.
|
||||
return u;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Array.<number>} code_points Array of code points.
|
||||
* @return {string} string String of UTF-16 code units.
|
||||
*/
|
||||
function codePointsToString(code_points) {
|
||||
var s = '';
|
||||
for (var i = 0; i < code_points.length; ++i) {
|
||||
var cp = code_points[i];
|
||||
if (cp <= 0xFFFF) {
|
||||
s += String.fromCharCode(cp);
|
||||
} else {
|
||||
cp -= 0x10000;
|
||||
s += String.fromCharCode((cp >> 10) + 0xD800,
|
||||
(cp & 0x3FF) + 0xDC00);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Implementation of Encoding specification
|
||||
// https://encoding.spec.whatwg.org/
|
||||
//
|
||||
|
||||
//
|
||||
// 3. Terminology
|
||||
//
|
||||
|
||||
/**
|
||||
* End-of-stream is a special token that signifies no more tokens
|
||||
* are in the stream.
|
||||
* @const
|
||||
*/ var end_of_stream = -1;
|
||||
|
||||
/**
|
||||
* A stream represents an ordered sequence of tokens.
|
||||
*
|
||||
* @constructor
|
||||
* @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
|
||||
* stream.
|
||||
*/
|
||||
function Stream(tokens) {
|
||||
/** @type {!Array.<number>} */
|
||||
this.tokens = [].slice.call(tokens);
|
||||
}
|
||||
|
||||
Stream.prototype = {
|
||||
/**
|
||||
* @return {boolean} True if end-of-stream has been hit.
|
||||
*/
|
||||
endOfStream: function() {
|
||||
return !this.tokens.length;
|
||||
},
|
||||
|
||||
/**
|
||||
* When a token is read from a stream, the first token in the
|
||||
* stream must be returned and subsequently removed, and
|
||||
* end-of-stream must be returned otherwise.
|
||||
*
|
||||
* @return {number} Get the next token from the stream, or
|
||||
* end_of_stream.
|
||||
*/
|
||||
read: function() {
|
||||
if (!this.tokens.length)
|
||||
return end_of_stream;
|
||||
return this.tokens.shift();
|
||||
},
|
||||
|
||||
/**
|
||||
* When one or more tokens are prepended to a stream, those tokens
|
||||
* must be inserted, in given order, before the first token in the
|
||||
* stream.
|
||||
*
|
||||
* @param {(number|!Array.<number>)} token The token(s) to prepend to the stream.
|
||||
*/
|
||||
prepend: function(token) {
|
||||
if (Array.isArray(token)) {
|
||||
var tokens = /**@type {!Array.<number>}*/(token);
|
||||
while (tokens.length)
|
||||
this.tokens.unshift(tokens.pop());
|
||||
} else {
|
||||
this.tokens.unshift(token);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* When one or more tokens are pushed to a stream, those tokens
|
||||
* must be inserted, in given order, after the last token in the
|
||||
* stream.
|
||||
*
|
||||
* @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
|
||||
*/
|
||||
push: function(token) {
|
||||
if (Array.isArray(token)) {
|
||||
var tokens = /**@type {!Array.<number>}*/(token);
|
||||
while (tokens.length)
|
||||
this.tokens.push(tokens.shift());
|
||||
} else {
|
||||
this.tokens.push(token);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// 4. Encodings
|
||||
//
|
||||
|
||||
// 4.1 Encoders and decoders
|
||||
|
||||
/** @const */
|
||||
var finished = -1;
|
||||
|
||||
/**
|
||||
* @param {boolean} fatal If true, decoding errors raise an exception.
|
||||
* @param {number=} opt_code_point Override the standard fallback code point.
|
||||
* @return {number} The code point to insert on a decoding error.
|
||||
*/
|
||||
function decoderError(fatal, opt_code_point) {
|
||||
if (fatal)
|
||||
throw TypeError('Decoder error');
|
||||
return opt_code_point || 0xFFFD;
|
||||
}
|
||||
|
||||
//
|
||||
// 7. API
|
||||
//
|
||||
|
||||
/** @const */ var DEFAULT_ENCODING = 'utf-8';
|
||||
|
||||
// 7.1 Interface TextDecoder
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* @param {string=} encoding The label of the encoding;
|
||||
* defaults to 'utf-8'.
|
||||
* @param {Object=} options
|
||||
*/
|
||||
function TextDecoder(encoding, options) {
|
||||
if (!(this instanceof TextDecoder)) {
|
||||
return new TextDecoder(encoding, options);
|
||||
}
|
||||
encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
|
||||
if (encoding !== DEFAULT_ENCODING) {
|
||||
throw new Error('Encoding not supported. Only utf-8 is supported');
|
||||
}
|
||||
options = ToDictionary(options);
|
||||
|
||||
/** @private @type {boolean} */
|
||||
this._streaming = false;
|
||||
/** @private @type {boolean} */
|
||||
this._BOMseen = false;
|
||||
/** @private @type {?Decoder} */
|
||||
this._decoder = null;
|
||||
/** @private @type {boolean} */
|
||||
this._fatal = Boolean(options['fatal']);
|
||||
/** @private @type {boolean} */
|
||||
this._ignoreBOM = Boolean(options['ignoreBOM']);
|
||||
|
||||
Object.defineProperty(this, 'encoding', {value: 'utf-8'});
|
||||
Object.defineProperty(this, 'fatal', {value: this._fatal});
|
||||
Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});
|
||||
}
|
||||
|
||||
TextDecoder.prototype = {
|
||||
/**
|
||||
* @param {ArrayBufferView=} input The buffer of bytes to decode.
|
||||
* @param {Object=} options
|
||||
* @return {string} The decoded string.
|
||||
*/
|
||||
decode: function decode(input, options) {
|
||||
var bytes;
|
||||
if (typeof input === 'object' && input instanceof ArrayBuffer) {
|
||||
bytes = new Uint8Array(input);
|
||||
} else if (typeof input === 'object' && 'buffer' in input &&
|
||||
input.buffer instanceof ArrayBuffer) {
|
||||
bytes = new Uint8Array(input.buffer,
|
||||
input.byteOffset,
|
||||
input.byteLength);
|
||||
} else {
|
||||
bytes = new Uint8Array(0);
|
||||
}
|
||||
|
||||
options = ToDictionary(options);
|
||||
|
||||
if (!this._streaming) {
|
||||
this._decoder = new UTF8Decoder({fatal: this._fatal});
|
||||
this._BOMseen = false;
|
||||
}
|
||||
this._streaming = Boolean(options['stream']);
|
||||
|
||||
var input_stream = new Stream(bytes);
|
||||
|
||||
var code_points = [];
|
||||
|
||||
/** @type {?(number|!Array.<number>)} */
|
||||
var result;
|
||||
|
||||
while (!input_stream.endOfStream()) {
|
||||
result = this._decoder.handler(input_stream, input_stream.read());
|
||||
if (result === finished)
|
||||
break;
|
||||
if (result === null)
|
||||
continue;
|
||||
if (Array.isArray(result))
|
||||
code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
|
||||
else
|
||||
code_points.push(result);
|
||||
}
|
||||
if (!this._streaming) {
|
||||
do {
|
||||
result = this._decoder.handler(input_stream, input_stream.read());
|
||||
if (result === finished)
|
||||
break;
|
||||
if (result === null)
|
||||
continue;
|
||||
if (Array.isArray(result))
|
||||
code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
|
||||
else
|
||||
code_points.push(result);
|
||||
} while (!input_stream.endOfStream());
|
||||
this._decoder = null;
|
||||
}
|
||||
|
||||
if (code_points.length) {
|
||||
// If encoding is one of utf-8, utf-16be, and utf-16le, and
|
||||
// ignore BOM flag and BOM seen flag are unset, run these
|
||||
// subsubsteps:
|
||||
if (['utf-8'].indexOf(this.encoding) !== -1 &&
|
||||
!this._ignoreBOM && !this._BOMseen) {
|
||||
// If token is U+FEFF, set BOM seen flag.
|
||||
if (code_points[0] === 0xFEFF) {
|
||||
this._BOMseen = true;
|
||||
code_points.shift();
|
||||
} else {
|
||||
// Otherwise, if token is not end-of-stream, set BOM seen
|
||||
// flag and append token to output.
|
||||
this._BOMseen = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return codePointsToString(code_points);
|
||||
}
|
||||
};
|
||||
|
||||
// 7.2 Interface TextEncoder
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* @param {string=} encoding The label of the encoding;
|
||||
* defaults to 'utf-8'.
|
||||
* @param {Object=} options
|
||||
*/
|
||||
function TextEncoder(encoding, options) {
|
||||
if (!(this instanceof TextEncoder))
|
||||
return new TextEncoder(encoding, options);
|
||||
encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
|
||||
if (encoding !== DEFAULT_ENCODING) {
|
||||
throw new Error('Encoding not supported. Only utf-8 is supported');
|
||||
}
|
||||
options = ToDictionary(options);
|
||||
|
||||
/** @private @type {boolean} */
|
||||
this._streaming = false;
|
||||
/** @private @type {?Encoder} */
|
||||
this._encoder = null;
|
||||
/** @private @type {{fatal: boolean}} */
|
||||
this._options = {fatal: Boolean(options['fatal'])};
|
||||
|
||||
Object.defineProperty(this, 'encoding', {value: 'utf-8'});
|
||||
}
|
||||
|
||||
TextEncoder.prototype = {
|
||||
/**
|
||||
* @param {string=} opt_string The string to encode.
|
||||
* @param {Object=} options
|
||||
* @return {Uint8Array} Encoded bytes, as a Uint8Array.
|
||||
*/
|
||||
encode: function encode(opt_string, options) {
|
||||
opt_string = opt_string ? String(opt_string) : '';
|
||||
options = ToDictionary(options);
|
||||
|
||||
// NOTE: This option is nonstandard. None of the encodings
|
||||
// permitted for encoding (i.e. UTF-8, UTF-16) are stateful,
|
||||
// so streaming is not necessary.
|
||||
if (!this._streaming)
|
||||
this._encoder = new UTF8Encoder(this._options);
|
||||
this._streaming = Boolean(options['stream']);
|
||||
|
||||
var bytes = [];
|
||||
var input_stream = new Stream(stringToCodePoints(opt_string));
|
||||
/** @type {?(number|!Array.<number>)} */
|
||||
var result;
|
||||
while (!input_stream.endOfStream()) {
|
||||
result = this._encoder.handler(input_stream, input_stream.read());
|
||||
if (result === finished)
|
||||
break;
|
||||
if (Array.isArray(result))
|
||||
bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
|
||||
else
|
||||
bytes.push(result);
|
||||
}
|
||||
if (!this._streaming) {
|
||||
while (true) {
|
||||
result = this._encoder.handler(input_stream, input_stream.read());
|
||||
if (result === finished)
|
||||
break;
|
||||
if (Array.isArray(result))
|
||||
bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
|
||||
else
|
||||
bytes.push(result);
|
||||
}
|
||||
this._encoder = null;
|
||||
}
|
||||
return new Uint8Array(bytes);
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// 8. The encoding
|
||||
//
|
||||
|
||||
// 8.1 utf-8
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* @implements {Decoder}
|
||||
* @param {{fatal: boolean}} options
|
||||
*/
|
||||
function UTF8Decoder(options) {
|
||||
var fatal = options.fatal;
|
||||
|
||||
// utf-8's decoder's has an associated utf-8 code point, utf-8
|
||||
// bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
|
||||
// lower boundary (initially 0x80), and a utf-8 upper boundary
|
||||
// (initially 0xBF).
|
||||
var /** @type {number} */ utf8_code_point = 0,
|
||||
/** @type {number} */ utf8_bytes_seen = 0,
|
||||
/** @type {number} */ utf8_bytes_needed = 0,
|
||||
/** @type {number} */ utf8_lower_boundary = 0x80,
|
||||
/** @type {number} */ utf8_upper_boundary = 0xBF;
|
||||
|
||||
/**
|
||||
* @param {Stream} stream The stream of bytes being decoded.
|
||||
* @param {number} bite The next byte read from the stream.
|
||||
* @return {?(number|!Array.<number>)} The next code point(s)
|
||||
* decoded, or null if not enough data exists in the input
|
||||
* stream to decode a complete code point.
|
||||
*/
|
||||
this.handler = function(stream, bite) {
|
||||
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
|
||||
// set utf-8 bytes needed to 0 and return error.
|
||||
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
|
||||
utf8_bytes_needed = 0;
|
||||
return decoderError(fatal);
|
||||
}
|
||||
|
||||
// 2. If byte is end-of-stream, return finished.
|
||||
if (bite === end_of_stream)
|
||||
return finished;
|
||||
|
||||
// 3. If utf-8 bytes needed is 0, based on byte:
|
||||
if (utf8_bytes_needed === 0) {
|
||||
|
||||
// 0x00 to 0x7F
|
||||
if (inRange(bite, 0x00, 0x7F)) {
|
||||
// Return a code point whose value is byte.
|
||||
return bite;
|
||||
}
|
||||
|
||||
// 0xC2 to 0xDF
|
||||
if (inRange(bite, 0xC2, 0xDF)) {
|
||||
// Set utf-8 bytes needed to 1 and utf-8 code point to byte
|
||||
// − 0xC0.
|
||||
utf8_bytes_needed = 1;
|
||||
utf8_code_point = bite - 0xC0;
|
||||
}
|
||||
|
||||
// 0xE0 to 0xEF
|
||||
else if (inRange(bite, 0xE0, 0xEF)) {
|
||||
// 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
|
||||
if (bite === 0xE0)
|
||||
utf8_lower_boundary = 0xA0;
|
||||
// 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
|
||||
if (bite === 0xED)
|
||||
utf8_upper_boundary = 0x9F;
|
||||
// 3. Set utf-8 bytes needed to 2 and utf-8 code point to
|
||||
// byte − 0xE0.
|
||||
utf8_bytes_needed = 2;
|
||||
utf8_code_point = bite - 0xE0;
|
||||
}
|
||||
|
||||
// 0xF0 to 0xF4
|
||||
else if (inRange(bite, 0xF0, 0xF4)) {
|
||||
// 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
|
||||
if (bite === 0xF0)
|
||||
utf8_lower_boundary = 0x90;
|
||||
// 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
|
||||
if (bite === 0xF4)
|
||||
utf8_upper_boundary = 0x8F;
|
||||
// 3. Set utf-8 bytes needed to 3 and utf-8 code point to
|
||||
// byte − 0xF0.
|
||||
utf8_bytes_needed = 3;
|
||||
utf8_code_point = bite - 0xF0;
|
||||
}
|
||||
|
||||
// Otherwise
|
||||
else {
|
||||
// Return error.
|
||||
return decoderError(fatal);
|
||||
}
|
||||
|
||||
// Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
|
||||
// point to utf-8 code point << (6 × utf-8 bytes needed) and
|
||||
// return continue.
|
||||
utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 4. If byte is not in the range utf-8 lower boundary to utf-8
|
||||
// upper boundary, run these substeps:
|
||||
if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
|
||||
|
||||
// 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
|
||||
// bytes seen to 0, set utf-8 lower boundary to 0x80, and set
|
||||
// utf-8 upper boundary to 0xBF.
|
||||
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
|
||||
utf8_lower_boundary = 0x80;
|
||||
utf8_upper_boundary = 0xBF;
|
||||
|
||||
// 2. Prepend byte to stream.
|
||||
stream.prepend(bite);
|
||||
|
||||
// 3. Return error.
|
||||
return decoderError(fatal);
|
||||
}
|
||||
|
||||
// 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
|
||||
// to 0xBF.
|
||||
utf8_lower_boundary = 0x80;
|
||||
utf8_upper_boundary = 0xBF;
|
||||
|
||||
// 6. Increase utf-8 bytes seen by one and set utf-8 code point
|
||||
// to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
|
||||
// needed − utf-8 bytes seen)).
|
||||
utf8_bytes_seen += 1;
|
||||
utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));
|
||||
|
||||
// 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
|
||||
// continue.
|
||||
if (utf8_bytes_seen !== utf8_bytes_needed)
|
||||
return null;
|
||||
|
||||
// 8. Let code point be utf-8 code point.
|
||||
var code_point = utf8_code_point;
|
||||
|
||||
// 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
|
||||
// seen to 0.
|
||||
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
|
||||
|
||||
// 10. Return a code point whose value is code point.
|
||||
return code_point;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* @implements {Encoder}
|
||||
* @param {{fatal: boolean}} options
|
||||
*/
|
||||
function UTF8Encoder(options) {
|
||||
var fatal = options.fatal;
|
||||
/**
|
||||
* @param {Stream} stream Input stream.
|
||||
* @param {number} code_point Next code point read from the stream.
|
||||
* @return {(number|!Array.<number>)} Byte(s) to emit.
|
||||
*/
|
||||
this.handler = function(stream, code_point) {
|
||||
// 1. If code point is end-of-stream, return finished.
|
||||
if (code_point === end_of_stream)
|
||||
return finished;
|
||||
|
||||
// 2. If code point is in the range U+0000 to U+007F, return a
|
||||
// byte whose value is code point.
|
||||
if (inRange(code_point, 0x0000, 0x007f))
|
||||
return code_point;
|
||||
|
||||
// 3. Set count and offset based on the range code point is in:
|
||||
var count, offset;
|
||||
// U+0080 to U+07FF: 1 and 0xC0
|
||||
if (inRange(code_point, 0x0080, 0x07FF)) {
|
||||
count = 1;
|
||||
offset = 0xC0;
|
||||
}
|
||||
// U+0800 to U+FFFF: 2 and 0xE0
|
||||
else if (inRange(code_point, 0x0800, 0xFFFF)) {
|
||||
count = 2;
|
||||
offset = 0xE0;
|
||||
}
|
||||
// U+10000 to U+10FFFF: 3 and 0xF0
|
||||
else if (inRange(code_point, 0x10000, 0x10FFFF)) {
|
||||
count = 3;
|
||||
offset = 0xF0;
|
||||
}
|
||||
|
||||
// 4.Let bytes be a byte sequence whose first byte is (code
|
||||
// point >> (6 × count)) + offset.
|
||||
var bytes = [(code_point >> (6 * count)) + offset];
|
||||
|
||||
// 5. Run these substeps while count is greater than 0:
|
||||
while (count > 0) {
|
||||
|
||||
// 1. Set temp to code point >> (6 × (count − 1)).
|
||||
var temp = code_point >> (6 * (count - 1));
|
||||
|
||||
// 2. Append to bytes 0x80 | (temp & 0x3F).
|
||||
bytes.push(0x80 | (temp & 0x3F));
|
||||
|
||||
// 3. Decrease count by one.
|
||||
count -= 1;
|
||||
}
|
||||
|
||||
// 6. Return bytes bytes, in order.
|
||||
return bytes;
|
||||
};
|
||||
}
|
||||
|
||||
exports.TextEncoder = TextEncoder;
|
||||
exports.TextDecoder = TextDecoder;
|
||||
@@ -0,0 +1,81 @@
|
||||
"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 () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useProvidedPrograms = useProvidedPrograms;
|
||||
exports.createProgramFromConfigFile = createProgramFromConfigFile;
|
||||
const tsconfig_utils_1 = require("@typescript-eslint/tsconfig-utils");
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const path = __importStar(require("node:path"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const shared_1 = require("./shared");
|
||||
const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:useProvidedPrograms');
|
||||
function useProvidedPrograms(programInstances, parseSettings) {
|
||||
log('Retrieving ast for %s from provided program instance(s)', parseSettings.filePath);
|
||||
let astAndProgram;
|
||||
for (const programInstance of programInstances) {
|
||||
astAndProgram = (0, shared_1.getAstFromProgram)(programInstance, parseSettings.filePath);
|
||||
// Stop at the first applicable program instance
|
||||
if (astAndProgram) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (astAndProgram) {
|
||||
astAndProgram.program.getTypeChecker(); // ensure parent pointers are set in source files
|
||||
return astAndProgram;
|
||||
}
|
||||
const relativeFilePath = path.relative(parseSettings.tsconfigRootDir, parseSettings.filePath);
|
||||
const [typeSource, typeSources] = parseSettings.projects.size > 0
|
||||
? ['project', 'project(s)']
|
||||
: ['programs', 'program instance(s)'];
|
||||
const errorLines = [
|
||||
`"parserOptions.${typeSource}" has been provided for @typescript-eslint/parser.`,
|
||||
`The file was not found in any of the provided ${typeSources}: ${relativeFilePath}`,
|
||||
];
|
||||
throw new Error(errorLines.join('\n'));
|
||||
}
|
||||
/**
|
||||
* 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()`
|
||||
*/
|
||||
function createProgramFromConfigFile(configFile, projectDirectory) {
|
||||
const parsed = (0, tsconfig_utils_1.getParsedConfigFile)(ts, configFile, projectDirectory);
|
||||
const host = ts.createCompilerHost(parsed.options, true);
|
||||
return ts.createProgram(parsed.fileNames, parsed.options, host);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
class Node {
|
||||
/// value;
|
||||
/// next;
|
||||
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
|
||||
// TODO: Remove this when targeting Node.js 12.
|
||||
this.next = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
class Queue {
|
||||
// TODO: Use private class fields when targeting Node.js 12.
|
||||
// #_head;
|
||||
// #_tail;
|
||||
// #_size;
|
||||
|
||||
constructor() {
|
||||
this.clear();
|
||||
}
|
||||
|
||||
enqueue(value) {
|
||||
const node = new Node(value);
|
||||
|
||||
if (this._head) {
|
||||
this._tail.next = node;
|
||||
this._tail = node;
|
||||
} else {
|
||||
this._head = node;
|
||||
this._tail = node;
|
||||
}
|
||||
|
||||
this._size++;
|
||||
}
|
||||
|
||||
dequeue() {
|
||||
const current = this._head;
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._head = this._head.next;
|
||||
this._size--;
|
||||
return current.value;
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._head = undefined;
|
||||
this._tail = undefined;
|
||||
this._size = 0;
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this._size;
|
||||
}
|
||||
|
||||
* [Symbol.iterator]() {
|
||||
let current = this._head;
|
||||
|
||||
while (current) {
|
||||
yield current.value;
|
||||
current = current.next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Queue;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ESLintUtils } from '@typescript-eslint/utils';
|
||||
export * from './astUtils';
|
||||
export * from './baseTypeUtils';
|
||||
export * from './collectUnusedVariables';
|
||||
export * from './createRule';
|
||||
export * from './getBaseTypesOfClassMember';
|
||||
export * from './getFixOrSuggest';
|
||||
export * from './getFunctionHeadLoc';
|
||||
export * from './getOperatorPrecedence';
|
||||
export * from './getStaticStringValue';
|
||||
export * from './getStringLength';
|
||||
export * from './getTextWithParentheses';
|
||||
export * from './getThisExpression';
|
||||
export * from './getWrappingFixer';
|
||||
export * from './hasOverloadSignatures';
|
||||
export * from './isArrayMethodCallWithPredicate';
|
||||
export * from './isAssignee';
|
||||
export * from './isConditionalTest';
|
||||
export * from './isNodeEqual';
|
||||
export * from './isNullLiteral';
|
||||
export * from './isStartOfExpressionStatement';
|
||||
export * from './isUndefinedIdentifier';
|
||||
export * from './misc';
|
||||
export * from './needsPrecedingSemiColon';
|
||||
export * from './objectIterators';
|
||||
export * from './needsToBeAwaited';
|
||||
export * from './scopeUtils';
|
||||
export * from './types';
|
||||
export * from './getConstraintInfo';
|
||||
export * from './getValueOfLiteralType';
|
||||
export * from './isHigherPrecedenceThanAwait';
|
||||
export * from './skipChainExpression';
|
||||
export * from './truthinessUtils';
|
||||
export * from './walkStatements';
|
||||
export * from '@typescript-eslint/type-utils';
|
||||
export declare const applyDefault: typeof ESLintUtils.applyDefault, deepMerge: typeof ESLintUtils.deepMerge, getParserServices: typeof ESLintUtils.getParserServices, isObjectNotArray: typeof ESLintUtils.isObjectNotArray, nullThrows: typeof ESLintUtils.nullThrows, NullThrowsReasons: {
|
||||
readonly MissingParent: 'Expected node to have a parent.';
|
||||
readonly MissingToken: (token: string, thing: string) => string;
|
||||
};
|
||||
export type InferMessageIdsTypeFromRule<T> = ESLintUtils.InferMessageIdsTypeFromRule<T>;
|
||||
export type InferOptionsTypeFromRule<T> = ESLintUtils.InferOptionsTypeFromRule<T>;
|
||||
@@ -0,0 +1,105 @@
|
||||
# eslint-visitor-keys
|
||||
|
||||
[](https://www.npmjs.com/package/eslint-visitor-keys)
|
||||
[](http://www.npmtrends.com/eslint-visitor-keys)
|
||||
[](https://github.com/eslint/eslint-visitor-keys/actions)
|
||||
|
||||
Constants and utilities about visitor keys to traverse AST.
|
||||
|
||||
## 💿 Installation
|
||||
|
||||
Use [npm] to install.
|
||||
|
||||
```bash
|
||||
$ npm install eslint-visitor-keys
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0`
|
||||
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
To use in an ESM file:
|
||||
|
||||
```js
|
||||
import * as evk from "eslint-visitor-keys"
|
||||
```
|
||||
|
||||
To use in a CommonJS file:
|
||||
|
||||
```js
|
||||
const evk = require("eslint-visitor-keys")
|
||||
```
|
||||
|
||||
### evk.KEYS
|
||||
|
||||
> type: `{ [type: string]: string[] | undefined }`
|
||||
|
||||
Visitor keys. This keys are frozen.
|
||||
|
||||
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
|
||||
```
|
||||
|
||||
### evk.getKeys(node)
|
||||
|
||||
> type: `(node: object) => string[]`
|
||||
|
||||
Get the visitor keys of a given AST node.
|
||||
|
||||
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
|
||||
|
||||
This will be used to traverse unknown nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
const node = {
|
||||
type: "AssignmentExpression",
|
||||
left: { type: "Identifier", name: "foo" },
|
||||
right: { type: "Literal", value: 0 }
|
||||
}
|
||||
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
|
||||
```
|
||||
|
||||
### evk.unionWith(additionalKeys)
|
||||
|
||||
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
|
||||
|
||||
Make the union set with `evk.KEYS` and the given keys.
|
||||
|
||||
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
|
||||
- It removes duplicated keys as keeping the first one.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
console.log(evk.unionWith({
|
||||
MethodDefinition: ["decorators"]
|
||||
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
|
||||
```
|
||||
|
||||
## 📰 Change log
|
||||
|
||||
See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases).
|
||||
|
||||
## 🍻 Contributing
|
||||
|
||||
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
|
||||
|
||||
### Development commands
|
||||
|
||||
- `npm test` runs tests and measures code coverage.
|
||||
- `npm run lint` checks source codes with ESLint.
|
||||
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
|
||||
|
||||
|
||||
[npm]: https://www.npmjs.com/
|
||||
[Node.js]: https://nodejs.org/
|
||||
[ESTree]: https://github.com/estree/estree
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_initializer_warning_helper.js";
|
||||
@@ -0,0 +1,47 @@
|
||||
export interface AssetMetadata {
|
||||
importedAssets: Set<string>
|
||||
importedCss: Set<string>
|
||||
}
|
||||
|
||||
export interface ChunkMetadata {
|
||||
importedAssets: Set<string>
|
||||
importedCss: Set<string>
|
||||
/** @internal */
|
||||
__modules: any
|
||||
}
|
||||
|
||||
export interface CustomPluginOptionsVite {
|
||||
/**
|
||||
* If this is a CSS Rollup module, you can scope to its importer's exports
|
||||
* so that if those exports are treeshaken away, the CSS module will also
|
||||
* be treeshaken.
|
||||
*
|
||||
* The "importerId" must import the CSS Rollup module statically.
|
||||
*
|
||||
* Example config if the CSS id is `/src/App.vue?vue&type=style&lang.css`:
|
||||
* ```js
|
||||
* cssScopeTo: ['/src/App.vue', 'default']
|
||||
* ```
|
||||
*/
|
||||
cssScopeTo?: readonly [importerId: string, exportName: string | undefined]
|
||||
|
||||
/** @deprecated no-op since Vite 6.1 */
|
||||
lang?: string
|
||||
}
|
||||
|
||||
declare module 'rolldown' {
|
||||
export interface OutputAsset {
|
||||
viteMetadata?: AssetMetadata
|
||||
}
|
||||
|
||||
export interface RenderedChunk {
|
||||
viteMetadata?: ChunkMetadata
|
||||
}
|
||||
export interface OutputChunk {
|
||||
viteMetadata?: ChunkMetadata
|
||||
}
|
||||
|
||||
export interface CustomPluginOptions {
|
||||
vite?: CustomPluginOptionsVite
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/**
|
||||
* @fileoverview Main CLI object.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
/*
|
||||
* NOTE: The CLI object should *not* call process.exit() directly. It should only return
|
||||
* exit codes. This allows other programs to use the CLI object and still control
|
||||
* when the program exits.
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const fs = require("node:fs"),
|
||||
{ mkdir, stat, writeFile } = require("node:fs/promises"),
|
||||
path = require("node:path"),
|
||||
{ pathToFileURL } = require("node:url"),
|
||||
{ ESLint, locateConfigFileToUse } = require("./eslint/eslint"),
|
||||
createCLIOptions = require("./options"),
|
||||
log = require("./shared/logging"),
|
||||
RuntimeInfo = require("./shared/runtime-info"),
|
||||
translateOptions = require("./shared/translate-cli-options");
|
||||
const { getCacheFile } = require("./eslint/eslint-helpers");
|
||||
const { SuppressionsService } = require("./services/suppressions-service");
|
||||
const debug = require("debug")("eslint:cli");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */
|
||||
/** @typedef {import("./types").ESLint.LintResult} LintResult */
|
||||
/** @typedef {import("./types").ESLint.ResultsMeta} ResultsMeta */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Count error messages.
|
||||
* @param {LintResult[]} results The lint results.
|
||||
* @returns {{errorCount:number;fatalErrorCount:number,warningCount:number}} The number of error messages.
|
||||
*/
|
||||
function countErrors(results) {
|
||||
let errorCount = 0;
|
||||
let fatalErrorCount = 0;
|
||||
let warningCount = 0;
|
||||
|
||||
for (const result of results) {
|
||||
errorCount += result.errorCount;
|
||||
fatalErrorCount += result.fatalErrorCount;
|
||||
warningCount += result.warningCount;
|
||||
}
|
||||
|
||||
return { errorCount, fatalErrorCount, warningCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an options module from the provided CLI options and encodes it as a data URL.
|
||||
* @param {ParsedCLIOptions} options The CLI options.
|
||||
* @returns {URL} The URL of the options module.
|
||||
*/
|
||||
function createOptionsModule(options) {
|
||||
const translateOptionsFileURL = new URL(
|
||||
"./shared/translate-cli-options.js",
|
||||
pathToFileURL(__filename),
|
||||
).href;
|
||||
const optionsSrc =
|
||||
`import translateOptions from ${JSON.stringify(translateOptionsFileURL)};\n` +
|
||||
`export default await translateOptions(${JSON.stringify(options)});\n`;
|
||||
|
||||
// Base64 encoding is typically shorter than URL encoding
|
||||
return new URL(
|
||||
`data:text/javascript;base64,${Buffer.from(optionsSrc).toString("base64")}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given file path is a directory or not.
|
||||
* @param {string} filePath The path to a file to check.
|
||||
* @returns {Promise<boolean>} `true` if the given path is a directory.
|
||||
*/
|
||||
async function isDirectory(filePath) {
|
||||
try {
|
||||
return (await stat(filePath)).isDirectory();
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs the results of the linting.
|
||||
* @param {ESLint} engine The ESLint instance to use.
|
||||
* @param {LintResult[]} results The results to print.
|
||||
* @param {string} format The name of the formatter to use or the path to the formatter.
|
||||
* @param {string} outputFile The path for the output file.
|
||||
* @param {ResultsMeta} resultsMeta Warning count and max threshold.
|
||||
* @returns {Promise<boolean>} True if the printing succeeds, false if not.
|
||||
* @private
|
||||
*/
|
||||
async function printResults(engine, results, format, outputFile, resultsMeta) {
|
||||
let formatter;
|
||||
|
||||
try {
|
||||
formatter = await engine.loadFormatter(format);
|
||||
} catch (e) {
|
||||
log.error(e.message);
|
||||
return false;
|
||||
}
|
||||
|
||||
const output = await formatter.format(results, resultsMeta);
|
||||
|
||||
if (outputFile) {
|
||||
const filePath = path.resolve(process.cwd(), outputFile);
|
||||
|
||||
if (await isDirectory(filePath)) {
|
||||
log.error(
|
||||
"Cannot write to output file path, it is a directory: %s",
|
||||
outputFile,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await mkdir(path.dirname(filePath), { recursive: true });
|
||||
await writeFile(filePath, output);
|
||||
} catch (ex) {
|
||||
log.error("There was a problem writing the output file:\n%s", ex);
|
||||
return false;
|
||||
}
|
||||
} else if (output) {
|
||||
log.info(output);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the `--concurrency` flag value.
|
||||
* @param {string} concurrency The `--concurrency` flag value to validate.
|
||||
* @returns {void}
|
||||
* @throws {Error} If the `--concurrency` flag value is invalid.
|
||||
*/
|
||||
function validateConcurrency(concurrency) {
|
||||
if (
|
||||
concurrency === void 0 ||
|
||||
concurrency === "auto" ||
|
||||
concurrency === "off"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const concurrencyValue = Number(concurrency);
|
||||
|
||||
if (!Number.isInteger(concurrencyValue) || concurrencyValue < 1) {
|
||||
throw new Error(
|
||||
`Option concurrency: '${concurrency}' is not a positive integer, 'auto' or 'off'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
|
||||
* for other Node.js programs to effectively run the CLI.
|
||||
*/
|
||||
const cli = {
|
||||
/**
|
||||
* Calculates the command string for the --inspect-config operation.
|
||||
* @param {string} configFile The path to the config file to inspect.
|
||||
* @returns {Promise<string>} The command string to execute.
|
||||
*/
|
||||
async calculateInspectConfigFlags(configFile) {
|
||||
// find the config file
|
||||
const { configFilePath, basePath } = await locateConfigFileToUse({
|
||||
cwd: process.cwd(),
|
||||
configFile,
|
||||
});
|
||||
|
||||
return ["--config", configFilePath, "--basePath", basePath];
|
||||
},
|
||||
|
||||
/**
|
||||
* Executes the CLI based on an array of arguments that is passed in.
|
||||
* @param {string|Array|Object} args The arguments to process.
|
||||
* @param {string} [text] The text to lint (used for TTY).
|
||||
* @returns {Promise<number>} The exit code for the operation.
|
||||
*/
|
||||
async execute(args, text) {
|
||||
if (Array.isArray(args)) {
|
||||
debug("CLI args: %o", args.slice(2));
|
||||
}
|
||||
|
||||
const CLIOptions = createCLIOptions();
|
||||
|
||||
/** @type {ParsedCLIOptions} */
|
||||
let options;
|
||||
|
||||
try {
|
||||
options = CLIOptions.parse(args);
|
||||
validateConcurrency(options.concurrency);
|
||||
} catch (error) {
|
||||
log.error(error.message);
|
||||
return 2;
|
||||
}
|
||||
|
||||
const files = options._;
|
||||
const useStdin = typeof text === "string";
|
||||
|
||||
if (options.help) {
|
||||
log.info(CLIOptions.generateHelp());
|
||||
return 0;
|
||||
}
|
||||
if (options.version) {
|
||||
log.info(RuntimeInfo.version());
|
||||
return 0;
|
||||
}
|
||||
if (options.envInfo) {
|
||||
try {
|
||||
log.info(RuntimeInfo.environment());
|
||||
return 0;
|
||||
} catch (err) {
|
||||
debug("Error retrieving environment info");
|
||||
log.error(err.message);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.printConfig) {
|
||||
if (files.length) {
|
||||
log.error(
|
||||
"The --print-config option must be used with exactly one file name.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
if (useStdin) {
|
||||
log.error(
|
||||
"The --print-config option is not available for piped-in code.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
const engine = new ESLint(await translateOptions(options));
|
||||
const fileConfig = await engine.calculateConfigForFile(
|
||||
options.printConfig,
|
||||
);
|
||||
|
||||
log.info(JSON.stringify(fileConfig, null, " "));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (options.inspectConfig) {
|
||||
log.info(
|
||||
"You can also run this command directly using 'npx @eslint/config-inspector@latest' in the same directory as your configuration file.",
|
||||
);
|
||||
|
||||
try {
|
||||
const flatOptions = await translateOptions(options);
|
||||
const spawn = require("cross-spawn");
|
||||
const flags = await cli.calculateInspectConfigFlags(
|
||||
flatOptions.overrideConfigFile,
|
||||
);
|
||||
|
||||
spawn.sync(
|
||||
"npx",
|
||||
["@eslint/config-inspector@latest", ...flags],
|
||||
{ encoding: "utf8", stdio: "inherit" },
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(error);
|
||||
return 2;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
debug(`Running on ${useStdin ? "text" : "files"}`);
|
||||
|
||||
if (options.fix && options.fixDryRun) {
|
||||
log.error(
|
||||
"The --fix option and the --fix-dry-run option cannot be used together.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
if (useStdin && options.fix) {
|
||||
log.error(
|
||||
"The --fix option is not available for piped-in code; use --fix-dry-run instead.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
if (options.fixType && !options.fix && !options.fixDryRun) {
|
||||
log.error(
|
||||
"The --fix-type option requires either --fix or --fix-dry-run.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (
|
||||
options.reportUnusedDisableDirectives &&
|
||||
options.reportUnusedDisableDirectivesSeverity !== void 0
|
||||
) {
|
||||
log.error(
|
||||
"The --report-unused-disable-directives option and the --report-unused-disable-directives-severity option cannot be used together.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (options.ext) {
|
||||
// Passing `--ext ""` results in `options.ext` being an empty array.
|
||||
if (options.ext.length === 0) {
|
||||
log.error("The --ext option value cannot be empty.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Passing `--ext ,ts` results in an empty string at index 0. Passing `--ext ts,,tsx` results in an empty string at index 1.
|
||||
const emptyStringIndex = options.ext.indexOf("");
|
||||
|
||||
if (emptyStringIndex >= 0) {
|
||||
log.error(
|
||||
`The --ext option arguments cannot be empty strings. Found an empty string at index ${emptyStringIndex}.`,
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.suppressAll && options.suppressRule) {
|
||||
log.error(
|
||||
"The --suppress-all option and the --suppress-rule option cannot be used together.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (options.suppressAll && options.pruneSuppressions) {
|
||||
log.error(
|
||||
"The --suppress-all option and the --prune-suppressions option cannot be used together.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (options.suppressRule && options.pruneSuppressions) {
|
||||
log.error(
|
||||
"The --suppress-rule option and the --prune-suppressions option cannot be used together.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (
|
||||
useStdin &&
|
||||
(options.suppressAll ||
|
||||
options.suppressRule ||
|
||||
options.pruneSuppressions)
|
||||
) {
|
||||
log.error(
|
||||
"The --suppress-all, --suppress-rule, and --prune-suppressions options cannot be used with piped-in code.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
/** @type {ESLint} */
|
||||
let engine;
|
||||
|
||||
if (options.concurrency !== "off") {
|
||||
const optionsURL = createOptionsModule(options);
|
||||
engine = await ESLint.fromOptionsModule(optionsURL);
|
||||
} else {
|
||||
const eslintOptions = await translateOptions(options);
|
||||
engine = new ESLint(eslintOptions);
|
||||
}
|
||||
let results;
|
||||
|
||||
if (useStdin) {
|
||||
results = await engine.lintText(text, {
|
||||
filePath: options.stdinFilename,
|
||||
});
|
||||
} else {
|
||||
results = await engine.lintFiles(files);
|
||||
}
|
||||
|
||||
if (options.fix) {
|
||||
debug("Fix mode enabled - applying fixes");
|
||||
await ESLint.outputFixes(results);
|
||||
}
|
||||
|
||||
let unusedSuppressions = {};
|
||||
|
||||
if (!useStdin) {
|
||||
const suppressionsFileLocation = getCacheFile(
|
||||
options.suppressionsLocation ||
|
||||
SuppressionsService.DEFAULT_SUPPRESSIONS_FILENAME,
|
||||
process.cwd(),
|
||||
{
|
||||
prefix: "suppressions_",
|
||||
},
|
||||
);
|
||||
|
||||
if (
|
||||
options.suppressionsLocation &&
|
||||
!fs.existsSync(suppressionsFileLocation) &&
|
||||
!options.suppressAll &&
|
||||
!options.suppressRule
|
||||
) {
|
||||
log.error(
|
||||
"The suppressions file does not exist. Please run the command with `--suppress-all` or `--suppress-rule` to create it.",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (
|
||||
options.suppressAll ||
|
||||
options.suppressRule ||
|
||||
options.pruneSuppressions ||
|
||||
fs.existsSync(suppressionsFileLocation)
|
||||
) {
|
||||
const suppressions = new SuppressionsService({
|
||||
filePath: suppressionsFileLocation,
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
if (options.suppressAll || options.suppressRule) {
|
||||
await suppressions.suppress(results, options.suppressRule);
|
||||
}
|
||||
|
||||
if (options.pruneSuppressions) {
|
||||
await suppressions.prune(results);
|
||||
}
|
||||
|
||||
const suppressionResults = suppressions.applySuppressions(
|
||||
results,
|
||||
await suppressions.load(),
|
||||
);
|
||||
|
||||
results = suppressionResults.results;
|
||||
unusedSuppressions = suppressionResults.unused;
|
||||
}
|
||||
}
|
||||
|
||||
let resultsToPrint = results;
|
||||
|
||||
if (options.quiet) {
|
||||
debug("Quiet mode enabled - filtering out warnings");
|
||||
resultsToPrint = ESLint.getErrorResults(resultsToPrint);
|
||||
}
|
||||
|
||||
const resultCounts = countErrors(results);
|
||||
const tooManyWarnings =
|
||||
options.maxWarnings >= 0 &&
|
||||
resultCounts.warningCount > options.maxWarnings;
|
||||
const resultsMeta = /** @type {ResultsMeta} */ ({});
|
||||
|
||||
/*
|
||||
* `--color` was set, `options.color` is `true`.
|
||||
* `--no-color` was set, `options.color` is `false`.
|
||||
* Neither option was provided, `options.color` is omitted, so `undefined`.
|
||||
*/
|
||||
if (options.color !== void 0) {
|
||||
debug(`Color setting for output: ${options.color}`);
|
||||
resultsMeta.color = options.color;
|
||||
}
|
||||
|
||||
if (tooManyWarnings) {
|
||||
resultsMeta.maxWarningsExceeded = {
|
||||
maxWarnings: options.maxWarnings,
|
||||
foundWarnings: resultCounts.warningCount,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
await printResults(
|
||||
engine,
|
||||
resultsToPrint,
|
||||
options.format,
|
||||
options.outputFile,
|
||||
resultsMeta,
|
||||
)
|
||||
) {
|
||||
// Errors and warnings from the original unfiltered results should determine the exit code
|
||||
const shouldExitForFatalErrors =
|
||||
options.exitOnFatalError && resultCounts.fatalErrorCount > 0;
|
||||
|
||||
if (!resultCounts.errorCount && tooManyWarnings) {
|
||||
log.error(
|
||||
"ESLint found too many warnings (maximum: %s).",
|
||||
options.maxWarnings,
|
||||
);
|
||||
}
|
||||
|
||||
if (!options.passOnUnprunedSuppressions) {
|
||||
const unusedSuppressionsCount =
|
||||
Object.keys(unusedSuppressions).length;
|
||||
|
||||
if (unusedSuppressionsCount > 0) {
|
||||
log.error(
|
||||
"There are suppressions left that do not occur anymore. To resolve this, re-run the command with `--prune-suppressions` to remove unused suppressions. To ignore unused suppressions, use `--pass-on-unpruned-suppressions`.",
|
||||
);
|
||||
debug(JSON.stringify(unusedSuppressions, null, 2));
|
||||
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldExitForFatalErrors) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
return resultCounts.errorCount || tooManyWarnings ? 1 : 0;
|
||||
}
|
||||
|
||||
return 2;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = cli;
|
||||
@@ -0,0 +1,35 @@
|
||||
import type * as ts from 'typescript';
|
||||
export interface ConstraintTypeInfoUnconstrained {
|
||||
constraintType: undefined;
|
||||
isTypeParameter: true;
|
||||
}
|
||||
export interface ConstraintTypeInfoConstrained {
|
||||
constraintType: ts.Type;
|
||||
isTypeParameter: true;
|
||||
}
|
||||
export interface ConstraintTypeInfoNonGeneric {
|
||||
constraintType: ts.Type;
|
||||
isTypeParameter: false;
|
||||
}
|
||||
export type ConstraintTypeInfo = ConstraintTypeInfoConstrained | ConstraintTypeInfoNonGeneric | ConstraintTypeInfoUnconstrained;
|
||||
/**
|
||||
* Returns whether the type is a generic and what its constraint is.
|
||||
*
|
||||
* If the type is not a generic, `isTypeParameter` will be `false`, and
|
||||
* `constraintType` will be the same as the input type.
|
||||
*
|
||||
* If the type is a generic, and it is constrained, `isTypeParameter` will be
|
||||
* `true`, and `constraintType` will be the constraint type.
|
||||
*
|
||||
* If the type is a generic, but it is not constrained, `constraintType` will be
|
||||
* `undefined` (rather than an `unknown` type), due to https://github.com/microsoft/TypeScript/issues/60475
|
||||
*
|
||||
* Successor to {@link getConstrainedTypeAtLocation} due to https://github.com/typescript-eslint/typescript-eslint/issues/10438
|
||||
*
|
||||
* This is considered internal since it is unstable for now and may have breaking changes at any time.
|
||||
* Use at your own risk.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
*/
|
||||
export declare function getConstraintInfo(checker: ts.TypeChecker, type: ts.Type): ConstraintTypeInfo;
|
||||
@@ -0,0 +1,6 @@
|
||||
export type Options = [('method' | 'property')?];
|
||||
export type MessageIds = 'convertToMethodSignature' | 'errorMethod' | 'errorProperty';
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,6 @@
|
||||
function _class_apply_descriptor_get(receiver, descriptor) {
|
||||
if (descriptor.get) return descriptor.get.call(receiver);
|
||||
|
||||
return descriptor.value;
|
||||
}
|
||||
export { _class_apply_descriptor_get as _ };
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
import type * as ts from 'typescript';
|
||||
/**
|
||||
* Does a simple check to see if there is an any being assigned to a non-any type.
|
||||
*
|
||||
* This also checks generic positions to ensure there's no unsafe sub-assignments.
|
||||
* Note: in the case of generic positions, it makes the assumption that the two types are the same.
|
||||
*
|
||||
* @example See tests for examples
|
||||
*
|
||||
* @returns false if it's safe, or an object with the two types if it's unsafe
|
||||
*/
|
||||
export declare function isUnsafeAssignment(type: ts.Type, receiver: ts.Type, checker: ts.TypeChecker, senderNode: TSESTree.Node | null): false | {
|
||||
receiver: ts.Type;
|
||||
sender: ts.Type;
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_throw.js";
|
||||
@@ -0,0 +1,132 @@
|
||||
export var CharacterCodes;
|
||||
(function (CharacterCodes) {
|
||||
CharacterCodes[CharacterCodes["EOF"] = -1] = "EOF";
|
||||
CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
|
||||
CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
|
||||
CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
|
||||
CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
|
||||
CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
|
||||
CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
|
||||
CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
|
||||
// Unicode 3.0 space characters
|
||||
CharacterCodes[CharacterCodes["space"] = 32] = "space";
|
||||
CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
|
||||
CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
|
||||
CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
|
||||
CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
|
||||
CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
|
||||
CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
|
||||
CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
|
||||
CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
|
||||
CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
|
||||
CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
|
||||
CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
|
||||
CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
|
||||
CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
|
||||
CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
|
||||
CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
|
||||
CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
|
||||
CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
|
||||
// Unicode replacement character produced when a byte sequence is invalid
|
||||
CharacterCodes[CharacterCodes["replacementCharacter"] = 65533] = "replacementCharacter";
|
||||
CharacterCodes[CharacterCodes["_"] = 95] = "_";
|
||||
CharacterCodes[CharacterCodes["$"] = 36] = "$";
|
||||
CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
|
||||
CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
|
||||
CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
|
||||
CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
|
||||
CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
|
||||
CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
|
||||
CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
|
||||
CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
|
||||
CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
|
||||
CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
|
||||
CharacterCodes[CharacterCodes["a"] = 97] = "a";
|
||||
CharacterCodes[CharacterCodes["b"] = 98] = "b";
|
||||
CharacterCodes[CharacterCodes["c"] = 99] = "c";
|
||||
CharacterCodes[CharacterCodes["d"] = 100] = "d";
|
||||
CharacterCodes[CharacterCodes["e"] = 101] = "e";
|
||||
CharacterCodes[CharacterCodes["f"] = 102] = "f";
|
||||
CharacterCodes[CharacterCodes["g"] = 103] = "g";
|
||||
CharacterCodes[CharacterCodes["h"] = 104] = "h";
|
||||
CharacterCodes[CharacterCodes["i"] = 105] = "i";
|
||||
CharacterCodes[CharacterCodes["j"] = 106] = "j";
|
||||
CharacterCodes[CharacterCodes["k"] = 107] = "k";
|
||||
CharacterCodes[CharacterCodes["l"] = 108] = "l";
|
||||
CharacterCodes[CharacterCodes["m"] = 109] = "m";
|
||||
CharacterCodes[CharacterCodes["n"] = 110] = "n";
|
||||
CharacterCodes[CharacterCodes["o"] = 111] = "o";
|
||||
CharacterCodes[CharacterCodes["p"] = 112] = "p";
|
||||
CharacterCodes[CharacterCodes["q"] = 113] = "q";
|
||||
CharacterCodes[CharacterCodes["r"] = 114] = "r";
|
||||
CharacterCodes[CharacterCodes["s"] = 115] = "s";
|
||||
CharacterCodes[CharacterCodes["t"] = 116] = "t";
|
||||
CharacterCodes[CharacterCodes["u"] = 117] = "u";
|
||||
CharacterCodes[CharacterCodes["v"] = 118] = "v";
|
||||
CharacterCodes[CharacterCodes["w"] = 119] = "w";
|
||||
CharacterCodes[CharacterCodes["x"] = 120] = "x";
|
||||
CharacterCodes[CharacterCodes["y"] = 121] = "y";
|
||||
CharacterCodes[CharacterCodes["z"] = 122] = "z";
|
||||
CharacterCodes[CharacterCodes["A"] = 65] = "A";
|
||||
CharacterCodes[CharacterCodes["B"] = 66] = "B";
|
||||
CharacterCodes[CharacterCodes["C"] = 67] = "C";
|
||||
CharacterCodes[CharacterCodes["D"] = 68] = "D";
|
||||
CharacterCodes[CharacterCodes["E"] = 69] = "E";
|
||||
CharacterCodes[CharacterCodes["F"] = 70] = "F";
|
||||
CharacterCodes[CharacterCodes["G"] = 71] = "G";
|
||||
CharacterCodes[CharacterCodes["H"] = 72] = "H";
|
||||
CharacterCodes[CharacterCodes["I"] = 73] = "I";
|
||||
CharacterCodes[CharacterCodes["J"] = 74] = "J";
|
||||
CharacterCodes[CharacterCodes["K"] = 75] = "K";
|
||||
CharacterCodes[CharacterCodes["L"] = 76] = "L";
|
||||
CharacterCodes[CharacterCodes["M"] = 77] = "M";
|
||||
CharacterCodes[CharacterCodes["N"] = 78] = "N";
|
||||
CharacterCodes[CharacterCodes["O"] = 79] = "O";
|
||||
CharacterCodes[CharacterCodes["P"] = 80] = "P";
|
||||
CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
|
||||
CharacterCodes[CharacterCodes["R"] = 82] = "R";
|
||||
CharacterCodes[CharacterCodes["S"] = 83] = "S";
|
||||
CharacterCodes[CharacterCodes["T"] = 84] = "T";
|
||||
CharacterCodes[CharacterCodes["U"] = 85] = "U";
|
||||
CharacterCodes[CharacterCodes["V"] = 86] = "V";
|
||||
CharacterCodes[CharacterCodes["W"] = 87] = "W";
|
||||
CharacterCodes[CharacterCodes["X"] = 88] = "X";
|
||||
CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
|
||||
CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
|
||||
CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
|
||||
CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
|
||||
CharacterCodes[CharacterCodes["at"] = 64] = "at";
|
||||
CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
|
||||
CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
|
||||
CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
|
||||
CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
|
||||
CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
|
||||
CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
|
||||
CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
|
||||
CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
|
||||
CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
|
||||
CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
|
||||
CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
|
||||
CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
|
||||
CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
|
||||
CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
|
||||
CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
|
||||
CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
|
||||
CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
|
||||
CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
|
||||
CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
|
||||
CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
|
||||
CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
|
||||
CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
|
||||
CharacterCodes[CharacterCodes["question"] = 63] = "question";
|
||||
CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
|
||||
CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
|
||||
CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
|
||||
CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
|
||||
CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
|
||||
CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
|
||||
CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
|
||||
CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
|
||||
CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
|
||||
})(CharacterCodes || (CharacterCodes = {}));
|
||||
//# sourceMappingURL=characterCodes.enum.js.map
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
import '../dist/cli.mjs';
|
||||
@@ -0,0 +1,76 @@
|
||||
export declare enum TypeFlags {
|
||||
None = 0,
|
||||
Any = 1,
|
||||
Unknown = 2,
|
||||
Undefined = 4,
|
||||
Null = 8,
|
||||
Void = 16,
|
||||
String = 32,
|
||||
Number = 64,
|
||||
BigInt = 128,
|
||||
Boolean = 256,
|
||||
ESSymbol = 512,
|
||||
StringLiteral = 1024,
|
||||
NumberLiteral = 2048,
|
||||
BigIntLiteral = 4096,
|
||||
BooleanLiteral = 8192,
|
||||
UniqueESSymbol = 16384,
|
||||
EnumLiteral = 32768,
|
||||
Enum = 65536,
|
||||
NonPrimitive = 131072,
|
||||
Never = 262144,
|
||||
TypeParameter = 524288,
|
||||
Object = 1048576,
|
||||
Index = 2097152,
|
||||
TemplateLiteral = 4194304,
|
||||
StringMapping = 8388608,
|
||||
Substitution = 16777216,
|
||||
IndexedAccess = 33554432,
|
||||
Conditional = 67108864,
|
||||
Union = 134217728,
|
||||
Intersection = 268435456,
|
||||
Reserved1 = 536870912,
|
||||
Reserved2 = 1073741824,
|
||||
Reserved3 = -2147483648,
|
||||
AnyOrUnknown = 3,
|
||||
Nullable = 12,
|
||||
Literal = 15360,
|
||||
Unit = 97292,
|
||||
Freshable = 80896,
|
||||
StringOrNumberLiteral = 3072,
|
||||
StringOrNumberLiteralOrUnique = 19456,
|
||||
DefinitelyFalsy = 15388,
|
||||
PossiblyFalsy = 15868,
|
||||
Intrinsic = 393983,
|
||||
StringLike = 12583968,
|
||||
NumberLike = 67648,
|
||||
BigIntLike = 4224,
|
||||
BooleanLike = 8448,
|
||||
EnumLike = 98304,
|
||||
ESSymbolLike = 16896,
|
||||
VoidLike = 20,
|
||||
Primitive = 12713980,
|
||||
DefinitelyNonNullable = 13893600,
|
||||
DisjointDomains = 12812284,
|
||||
UnionOrIntersection = 402653184,
|
||||
StructuredType = 403701760,
|
||||
TypeVariable = 34078720,
|
||||
InstantiableNonPrimitive = 117964800,
|
||||
InstantiablePrimitive = 14680064,
|
||||
Instantiable = 132644864,
|
||||
StructuredOrInstantiable = 536346624,
|
||||
ObjectFlagsType = 403963917,
|
||||
Simplifiable = 102760448,
|
||||
Singleton = 394239,
|
||||
Narrowable = 536575971,
|
||||
IncludesMask = 416808959,
|
||||
IncludesMissingType = 524288,
|
||||
IncludesNonWideningType = 2097152,
|
||||
IncludesWildcard = 33554432,
|
||||
IncludesEmptyObject = 67108864,
|
||||
IncludesInstantiable = 16777216,
|
||||
IncludesConstrainedTypeVariable = 536870912,
|
||||
IncludesError = 1073741824,
|
||||
NotPrimitiveUnion = 286523411
|
||||
}
|
||||
//# sourceMappingURL=typeFlags.enum.d.ts.map
|
||||
@@ -0,0 +1,156 @@
|
||||
import * as util from "../core/util.js";
|
||||
function getBelarusianPlural(count, one, few, many) {
|
||||
const absCount = Math.abs(count);
|
||||
const lastDigit = absCount % 10;
|
||||
const lastTwoDigits = absCount % 100;
|
||||
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
|
||||
return many;
|
||||
}
|
||||
if (lastDigit === 1) {
|
||||
return one;
|
||||
}
|
||||
if (lastDigit >= 2 && lastDigit <= 4) {
|
||||
return few;
|
||||
}
|
||||
return many;
|
||||
}
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: {
|
||||
unit: {
|
||||
one: "сімвал",
|
||||
few: "сімвалы",
|
||||
many: "сімвалаў",
|
||||
},
|
||||
verb: "мець",
|
||||
},
|
||||
array: {
|
||||
unit: {
|
||||
one: "элемент",
|
||||
few: "элементы",
|
||||
many: "элементаў",
|
||||
},
|
||||
verb: "мець",
|
||||
},
|
||||
set: {
|
||||
unit: {
|
||||
one: "элемент",
|
||||
few: "элементы",
|
||||
many: "элементаў",
|
||||
},
|
||||
verb: "мець",
|
||||
},
|
||||
file: {
|
||||
unit: {
|
||||
one: "байт",
|
||||
few: "байты",
|
||||
many: "байтаў",
|
||||
},
|
||||
verb: "мець",
|
||||
},
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "увод",
|
||||
email: "email адрас",
|
||||
url: "URL",
|
||||
emoji: "эмодзі",
|
||||
uuid: "UUID",
|
||||
uuidv4: "UUIDv4",
|
||||
uuidv6: "UUIDv6",
|
||||
nanoid: "nanoid",
|
||||
guid: "GUID",
|
||||
cuid: "cuid",
|
||||
cuid2: "cuid2",
|
||||
ulid: "ULID",
|
||||
xid: "XID",
|
||||
ksuid: "KSUID",
|
||||
datetime: "ISO дата і час",
|
||||
date: "ISO дата",
|
||||
time: "ISO час",
|
||||
duration: "ISO працягласць",
|
||||
ipv4: "IPv4 адрас",
|
||||
ipv6: "IPv6 адрас",
|
||||
cidrv4: "IPv4 дыяпазон",
|
||||
cidrv6: "IPv6 дыяпазон",
|
||||
base64: "радок у фармаце base64",
|
||||
base64url: "радок у фармаце base64url",
|
||||
json_string: "JSON радок",
|
||||
e164: "нумар E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "увод",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "лік",
|
||||
array: "масіў",
|
||||
};
|
||||
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 `Няправільны ўвод: чакаўся instanceof ${issue.expected}, атрымана ${received}`;
|
||||
}
|
||||
return `Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Няправільны ўвод: чакалася ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Няправільны варыянт: чакаўся адзін з ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
const maxValue = Number(issue.maximum);
|
||||
const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
|
||||
return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`;
|
||||
}
|
||||
return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
const minValue = Number(issue.minimum);
|
||||
const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
|
||||
return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`;
|
||||
}
|
||||
return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;
|
||||
return `Няправільны ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Няправільны лік: павінен быць кратным ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Няправільны ключ у ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Няправільны ўвод";
|
||||
case "invalid_element":
|
||||
return `Няправільнае значэнне ў ${issue.origin}`;
|
||||
default:
|
||||
return `Няправільны ўвод`;
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { _ as _define_property } from "./_define_property.js";
|
||||
import { _ as _super_prop_base } from "./_super_prop_base.js";
|
||||
|
||||
function set(target, property, value, receiver) {
|
||||
if (typeof Reflect !== "undefined" && Reflect.set) set = Reflect.set;
|
||||
else {
|
||||
set = function set(target, property, value, receiver) {
|
||||
var base = _super_prop_base(target, property);
|
||||
var desc;
|
||||
if (base) {
|
||||
desc = Object.getOwnPropertyDescriptor(base, property);
|
||||
if (desc.set) {
|
||||
desc.set.call(receiver, value);
|
||||
|
||||
return true;
|
||||
} else if (!desc.writable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
desc = Object.getOwnPropertyDescriptor(receiver, property);
|
||||
if (desc) {
|
||||
if (!desc.writable) return false;
|
||||
desc.value = value;
|
||||
Object.defineProperty(receiver, property, desc);
|
||||
} else {
|
||||
_define_property(receiver, property, value);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
return set(target, property, value, receiver);
|
||||
}
|
||||
|
||||
function _set(target, property, value, receiver, isStrict) {
|
||||
var s = set(target, property, value, receiver || target);
|
||||
if (!s && isStrict) throw new Error("failed to set property");
|
||||
|
||||
return value;
|
||||
}
|
||||
export { _set as _ };
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as core from "./core.cjs";
|
||||
import * as errors from "./errors.cjs";
|
||||
import type * as schemas from "./schemas.cjs";
|
||||
import * as util from "./util.cjs";
|
||||
export type $ZodErrorClass = {
|
||||
new (issues: errors.$ZodIssue[]): errors.$ZodError;
|
||||
};
|
||||
export type $Parse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: {
|
||||
callee?: util.AnyFunc;
|
||||
Err?: $ZodErrorClass;
|
||||
}) => core.output<T>;
|
||||
export declare const _parse: (_Err: $ZodErrorClass) => $Parse;
|
||||
export declare const parse: $Parse;
|
||||
export type $ParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: {
|
||||
callee?: util.AnyFunc;
|
||||
Err?: $ZodErrorClass;
|
||||
}) => Promise<core.output<T>>;
|
||||
export declare const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync;
|
||||
export declare const parseAsync: $ParseAsync;
|
||||
export type $SafeParse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
|
||||
export declare const _safeParse: (_Err: $ZodErrorClass) => $SafeParse;
|
||||
export declare const safeParse: $SafeParse;
|
||||
export type $SafeParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
|
||||
export declare const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync;
|
||||
export declare const safeParseAsync: $SafeParseAsync;
|
||||
export type $Encode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => core.input<T>;
|
||||
export declare const _encode: (_Err: $ZodErrorClass) => $Encode;
|
||||
export declare const encode: $Encode;
|
||||
export type $Decode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => core.output<T>;
|
||||
export declare const _decode: (_Err: $ZodErrorClass) => $Decode;
|
||||
export declare const decode: $Decode;
|
||||
export type $EncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<core.input<T>>;
|
||||
export declare const _encodeAsync: (_Err: $ZodErrorClass) => $EncodeAsync;
|
||||
export declare const encodeAsync: $EncodeAsync;
|
||||
export type $DecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<core.output<T>>;
|
||||
export declare const _decodeAsync: (_Err: $ZodErrorClass) => $DecodeAsync;
|
||||
export declare const decodeAsync: $DecodeAsync;
|
||||
export type $SafeEncode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.input<T>>;
|
||||
export declare const _safeEncode: (_Err: $ZodErrorClass) => $SafeEncode;
|
||||
export declare const safeEncode: $SafeEncode;
|
||||
export type $SafeDecode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
|
||||
export declare const _safeDecode: (_Err: $ZodErrorClass) => $SafeDecode;
|
||||
export declare const safeDecode: $SafeDecode;
|
||||
export type $SafeEncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.input<T>>>;
|
||||
export declare const _safeEncodeAsync: (_Err: $ZodErrorClass) => $SafeEncodeAsync;
|
||||
export declare const safeEncodeAsync: $SafeEncodeAsync;
|
||||
export type $SafeDecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
|
||||
export declare const _safeDecodeAsync: (_Err: $ZodErrorClass) => $SafeDecodeAsync;
|
||||
export declare const safeDecodeAsync: $SafeDecodeAsync;
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
var test = require('tape');
|
||||
var parse = require('../');
|
||||
|
||||
test('long opts', function (t) {
|
||||
t.deepEqual(
|
||||
parse(['--bool']),
|
||||
{ bool: true, _: [] },
|
||||
'long boolean'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['--pow', 'xixxle']),
|
||||
{ pow: 'xixxle', _: [] },
|
||||
'long capture sp'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['--pow=xixxle']),
|
||||
{ pow: 'xixxle', _: [] },
|
||||
'long capture eq'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['--host', 'localhost', '--port', '555']),
|
||||
{ host: 'localhost', port: 555, _: [] },
|
||||
'long captures sp'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['--host=localhost', '--port=555']),
|
||||
{ host: 'localhost', port: 555, _: [] },
|
||||
'long captures eq'
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* PBKDF (RFC 2898). Can be used to create a key from password and salt.
|
||||
* @module
|
||||
*/
|
||||
import { hmac } from "./hmac.js";
|
||||
// prettier-ignore
|
||||
import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes } from "./utils.js";
|
||||
// Common prologue and epilogue for sync/async functions
|
||||
function pbkdf2Init(hash, _password, _salt, _opts) {
|
||||
ahash(hash);
|
||||
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
|
||||
const { c, dkLen, asyncTick } = opts;
|
||||
anumber(c);
|
||||
anumber(dkLen);
|
||||
anumber(asyncTick);
|
||||
if (c < 1)
|
||||
throw new Error('iterations (c) should be >= 1');
|
||||
const password = kdfInputToBytes(_password);
|
||||
const salt = kdfInputToBytes(_salt);
|
||||
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
|
||||
const DK = new Uint8Array(dkLen);
|
||||
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
||||
const PRF = hmac.create(hash, password);
|
||||
const PRFSalt = PRF._cloneInto().update(salt);
|
||||
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
|
||||
}
|
||||
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
|
||||
PRF.destroy();
|
||||
PRFSalt.destroy();
|
||||
if (prfW)
|
||||
prfW.destroy();
|
||||
clean(u);
|
||||
return DK;
|
||||
}
|
||||
/**
|
||||
* PBKDF2-HMAC: RFC 2898 key derivation function
|
||||
* @param hash - hash function that would be used e.g. sha256
|
||||
* @param password - password from which a derived key is generated
|
||||
* @param salt - cryptographic salt
|
||||
* @param opts - {c, dkLen} where c is work factor and dkLen is output message size
|
||||
* @example
|
||||
* const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
|
||||
*/
|
||||
export function pbkdf2(hash, password, salt, opts) {
|
||||
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
|
||||
let prfW; // Working copy
|
||||
const arr = new Uint8Array(4);
|
||||
const view = createView(arr);
|
||||
const u = new Uint8Array(PRF.outputLen);
|
||||
// DK = T1 + T2 + ⋯ + Tdklen/hlen
|
||||
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
|
||||
// Ti = F(Password, Salt, c, i)
|
||||
const Ti = DK.subarray(pos, pos + PRF.outputLen);
|
||||
view.setInt32(0, ti, false);
|
||||
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
|
||||
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
||||
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
|
||||
Ti.set(u.subarray(0, Ti.length));
|
||||
for (let ui = 1; ui < c; ui++) {
|
||||
// Uc = PRF(Password, Uc−1)
|
||||
PRF._cloneInto(prfW).update(u).digestInto(u);
|
||||
for (let i = 0; i < Ti.length; i++)
|
||||
Ti[i] ^= u[i];
|
||||
}
|
||||
}
|
||||
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
|
||||
}
|
||||
/**
|
||||
* PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
|
||||
* @example
|
||||
* await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
|
||||
*/
|
||||
export async function pbkdf2Async(hash, password, salt, opts) {
|
||||
const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
|
||||
let prfW; // Working copy
|
||||
const arr = new Uint8Array(4);
|
||||
const view = createView(arr);
|
||||
const u = new Uint8Array(PRF.outputLen);
|
||||
// DK = T1 + T2 + ⋯ + Tdklen/hlen
|
||||
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
|
||||
// Ti = F(Password, Salt, c, i)
|
||||
const Ti = DK.subarray(pos, pos + PRF.outputLen);
|
||||
view.setInt32(0, ti, false);
|
||||
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
|
||||
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
||||
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
|
||||
Ti.set(u.subarray(0, Ti.length));
|
||||
await asyncLoop(c - 1, asyncTick, () => {
|
||||
// Uc = PRF(Password, Uc−1)
|
||||
PRF._cloneInto(prfW).update(u).digestInto(u);
|
||||
for (let i = 0; i < Ti.length; i++)
|
||||
Ti[i] ^= u[i];
|
||||
});
|
||||
}
|
||||
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
|
||||
}
|
||||
//# sourceMappingURL=pbkdf2.js.map
|
||||
@@ -0,0 +1,47 @@
|
||||
let crypto = require('crypto')
|
||||
|
||||
let { urlAlphabet } = require('../url-alphabet/index.cjs')
|
||||
|
||||
let random = bytes =>
|
||||
new Promise((resolve, reject) => {
|
||||
crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve(buf)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
|
||||
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
|
||||
let tick = (id, size = defaultSize) =>
|
||||
random(step).then(bytes => {
|
||||
let i = step
|
||||
while (i--) {
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
if (id.length >= size) return id
|
||||
}
|
||||
return tick(id, size)
|
||||
})
|
||||
|
||||
return (size = defaultSize) => {
|
||||
if (size <= 0) return Promise.resolve('')
|
||||
return tick('', size)
|
||||
}
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) =>
|
||||
random((size |= 0)).then(bytes => {
|
||||
let id = ''
|
||||
while (size--) {
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
}
|
||||
return id
|
||||
})
|
||||
|
||||
module.exports = { nanoid, customAlphabet, random }
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2019_symbol: LibDefinition;
|
||||
@@ -0,0 +1,27 @@
|
||||
interface RuleMap {
|
||||
'arrow-parens': typeof import('eslint/lib/rules/arrow-parens');
|
||||
'consistent-return': typeof import('eslint/lib/rules/consistent-return');
|
||||
'dot-notation': typeof import('eslint/lib/rules/dot-notation');
|
||||
'init-declarations': typeof import('eslint/lib/rules/init-declarations');
|
||||
'max-params': typeof import('eslint/lib/rules/max-params');
|
||||
'no-dupe-args': typeof import('eslint/lib/rules/no-dupe-args');
|
||||
'no-dupe-class-members': typeof import('eslint/lib/rules/no-dupe-class-members');
|
||||
'no-empty-function': typeof import('eslint/lib/rules/no-empty-function');
|
||||
'no-implicit-globals': typeof import('eslint/lib/rules/no-implicit-globals');
|
||||
'no-invalid-this': typeof import('eslint/lib/rules/no-invalid-this');
|
||||
'no-loop-func': typeof import('eslint/lib/rules/no-loop-func');
|
||||
'no-loss-of-precision': typeof import('eslint/lib/rules/no-loss-of-precision');
|
||||
'no-magic-numbers': typeof import('eslint/lib/rules/no-magic-numbers');
|
||||
'no-restricted-globals': typeof import('eslint/lib/rules/no-restricted-globals');
|
||||
'no-restricted-imports': typeof import('eslint/lib/rules/no-restricted-imports');
|
||||
'no-undef': typeof import('eslint/lib/rules/no-undef');
|
||||
'no-unused-expressions': typeof import('eslint/lib/rules/no-unused-expressions');
|
||||
'no-useless-constructor': typeof import('eslint/lib/rules/no-useless-constructor');
|
||||
'prefer-const': typeof import('eslint/lib/rules/prefer-const');
|
||||
'prefer-destructuring': typeof import('eslint/lib/rules/prefer-destructuring');
|
||||
strict: typeof import('eslint/lib/rules/strict');
|
||||
}
|
||||
type RuleId = keyof RuleMap;
|
||||
export declare const getESLintCoreRule: <R extends RuleId>(ruleId: R) => RuleMap[R];
|
||||
export declare function maybeGetESLintCoreRule<R extends RuleId>(ruleId: R): RuleMap[R] | null;
|
||||
export {};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,206 @@
|
||||
import module$1, { isBuiltin } from 'node:module';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { automockModule, createManualModuleSource, collectModuleExports } from '@vitest/mocker/transforms';
|
||||
import { cleanUrl, createDefer } from '@vitest/utils/helpers';
|
||||
import { p as parse } from './acorn.B2iPLyUM.js';
|
||||
import { isAbsolute } from 'pathe';
|
||||
import { t as toBuiltin } from './modules.BJuCwlRJ.js';
|
||||
import { B as BareModuleMocker, n as normalizeModuleId } from './startVitestModuleRunner.DB-7oCpn.js';
|
||||
import 'node:fs';
|
||||
import './utils.BX5Fg8C4.js';
|
||||
import '@vitest/utils/timers';
|
||||
import '../path.js';
|
||||
import 'node:path';
|
||||
import '../module-evaluator.js';
|
||||
import 'node:vm';
|
||||
import 'vite/module-runner';
|
||||
import './traces.DT5aQ62U.js';
|
||||
import '@vitest/mocker';
|
||||
import '@vitest/mocker/redirect';
|
||||
|
||||
class NativeModuleMocker extends BareModuleMocker {
|
||||
wrapDynamicImport(moduleFactory) {
|
||||
if (typeof moduleFactory === "function") return new Promise((resolve, reject) => {
|
||||
this.resolveMocks().finally(() => {
|
||||
moduleFactory().then(resolve, reject);
|
||||
});
|
||||
});
|
||||
return moduleFactory;
|
||||
}
|
||||
resolveMockedModule(url, parentURL) {
|
||||
// don't mock modules inside of packages because there is
|
||||
// a high chance that it uses `require` which is not mockable
|
||||
// because we use top-level await in "manual" mocks.
|
||||
// for the sake of consistency we don't support mocking anything at all
|
||||
if (parentURL.includes("/node_modules/")) return;
|
||||
const moduleId = normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url);
|
||||
const mockedModule = this.getDependencyMock(moduleId);
|
||||
if (!mockedModule) return;
|
||||
if (mockedModule.type === "redirect") return {
|
||||
url: pathToFileURL(mockedModule.redirect).toString(),
|
||||
shortCircuit: true
|
||||
};
|
||||
if (mockedModule.type === "automock" || mockedModule.type === "autospy") return {
|
||||
url: injectQuery(url, parentURL, `mock=${mockedModule.type}`),
|
||||
shortCircuit: true
|
||||
};
|
||||
if (mockedModule.type === "manual") return {
|
||||
url: injectQuery(url, parentURL, "mock=manual"),
|
||||
shortCircuit: true
|
||||
};
|
||||
}
|
||||
loadAutomock(url, result) {
|
||||
const moduleId = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
|
||||
let source;
|
||||
if (isBuiltin(moduleId)) {
|
||||
const builtinModule = getBuiltinModule(moduleId);
|
||||
const exports$1 = Object.keys(builtinModule);
|
||||
source = `
|
||||
import * as builtinModule from '${toBuiltin(moduleId)}?mock=actual'
|
||||
|
||||
${exports$1.map((key, index) => {
|
||||
return `
|
||||
const __${index} = builtinModule["${key}"]
|
||||
export { __${index} as "${key}" }
|
||||
`;
|
||||
}).join("")}`;
|
||||
} else source = result.source?.toString();
|
||||
if (source == null) return;
|
||||
const mockType = url.includes("mock=automock") ? "automock" : "autospy";
|
||||
const transformedCode = transformCode(source, result.format || "module", moduleId);
|
||||
try {
|
||||
const ms = automockModule(transformedCode, mockType, (code) => parse(code, {
|
||||
sourceType: "module",
|
||||
ecmaVersion: "latest"
|
||||
}), { id: moduleId });
|
||||
return {
|
||||
format: "module",
|
||||
source: `${ms.toString()}\n//# sourceMappingURL=${genSourceMapUrl(ms.generateMap({
|
||||
hires: "boundary",
|
||||
source: moduleId
|
||||
}))}`,
|
||||
shortCircuit: true
|
||||
};
|
||||
} catch (cause) {
|
||||
throw new Error(`Cannot automock '${url}' because it failed to parse.`, { cause });
|
||||
}
|
||||
}
|
||||
loadManualMock(url, result) {
|
||||
const moduleId = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
|
||||
// should not be possible
|
||||
if (this.getDependencyMock(moduleId)?.type !== "manual") {
|
||||
console.warn(`Vitest detected unregistered manual mock ${moduleId}. This is a bug in Vitest. Please, open a new issue with reproduction.`);
|
||||
return;
|
||||
}
|
||||
if (isBuiltin(moduleId)) {
|
||||
const builtinModule = getBuiltinModule(toBuiltin(moduleId));
|
||||
return {
|
||||
format: "module",
|
||||
source: createManualModuleSource(moduleId, Object.keys(builtinModule)),
|
||||
shortCircuit: true
|
||||
};
|
||||
}
|
||||
if (!result.source) return;
|
||||
const transformedCode = transformCode(result.source.toString(), result.format || "module", moduleId);
|
||||
if (transformedCode == null) return;
|
||||
const format = result.format?.startsWith("module") ? "module" : "commonjs";
|
||||
try {
|
||||
return {
|
||||
format: "module",
|
||||
source: createManualModuleSource(moduleId, collectModuleExports(moduleId, transformedCode, format)),
|
||||
shortCircuit: true
|
||||
};
|
||||
} catch (cause) {
|
||||
throw new Error(`Failed to mock '${url}'. See the cause for more information.`, { cause });
|
||||
}
|
||||
}
|
||||
processedModules = /* @__PURE__ */ new Map();
|
||||
checkCircularManualMock(url) {
|
||||
const id = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
|
||||
this.processedModules.set(id, (this.processedModules.get(id) ?? 0) + 1);
|
||||
// the module is mocked and requested a second time, let's resolve
|
||||
// the factory function that will redefine the exports later
|
||||
if (this.originalModulePromises.has(id)) {
|
||||
const factoryPromise = this.factoryPromises.get(id);
|
||||
this.originalModulePromises.get(id)?.resolve({ __factoryPromise: factoryPromise });
|
||||
}
|
||||
}
|
||||
originalModulePromises = /* @__PURE__ */ new Map();
|
||||
factoryPromises = /* @__PURE__ */ new Map();
|
||||
// potential performance improvement:
|
||||
// store by URL, not ids, no need to call url.*to* methods and normalizeModuleId
|
||||
getFactoryModule(id) {
|
||||
const mock = this.getMockerRegistry().getById(id);
|
||||
if (!mock || mock.type !== "manual") throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
|
||||
const mockResult = mock.resolve();
|
||||
if (mockResult instanceof Promise) {
|
||||
// to avoid circular dependency, we resolve this function as {__factoryPromise} in `checkCircularManualMock`
|
||||
// when it's requested the second time. then the exports are exposed as `undefined`,
|
||||
// but later redefined when the promise is actually resolved
|
||||
const promise = createDefer();
|
||||
promise.finally(() => {
|
||||
this.originalModulePromises.delete(id);
|
||||
});
|
||||
mockResult.then(promise.resolve, promise.reject).finally(() => {
|
||||
this.factoryPromises.delete(id);
|
||||
});
|
||||
this.factoryPromises.set(id, mockResult);
|
||||
this.originalModulePromises.set(id, promise);
|
||||
// Node.js on windows processes all the files first, and then runs them
|
||||
// unlike Node.js logic on Mac and Unix where it also runs the code while evaluating
|
||||
// So on Linux/Mac this `if` won't be hit because `checkCircularManualMock` will resolve it
|
||||
// And on Windows, the `checkCircularManualMock` will never have `originalModulePromises`
|
||||
// because `getFactoryModule` is not called until the evaluation phase
|
||||
// But if we track how many times the module was transformed,
|
||||
// we can deduce when to return `__factoryPromise` to support circular modules
|
||||
if ((this.processedModules.get(id) ?? 0) > 1) {
|
||||
this.processedModules.set(id, (this.processedModules.get(id) ?? 1) - 1);
|
||||
promise.resolve({ __factoryPromise: mockResult });
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
return mockResult;
|
||||
}
|
||||
importActual(rawId, importer) {
|
||||
const resolvedId = import.meta.resolve(rawId, pathToFileURL(importer).toString());
|
||||
const url = new URL(resolvedId);
|
||||
url.searchParams.set("mock", "actual");
|
||||
return import(url.toString());
|
||||
}
|
||||
importMock(rawId, importer) {
|
||||
const resolvedId = import.meta.resolve(rawId, pathToFileURL(importer).toString());
|
||||
// file is already mocked
|
||||
if (resolvedId.includes("mock=")) return import(resolvedId);
|
||||
const filename = fileURLToPath(resolvedId);
|
||||
const external = !isAbsolute(filename) || this.isModuleDirectory(resolvedId) ? normalizeModuleId(rawId) : null;
|
||||
// file is not mocked, automock or redirect it
|
||||
const redirect = this.findMockRedirect(filename, external);
|
||||
if (redirect) return import(pathToFileURL(redirect).toString());
|
||||
const url = new URL(resolvedId);
|
||||
url.searchParams.set("mock", "automock");
|
||||
return import(url.toString());
|
||||
}
|
||||
}
|
||||
const replacePercentageRE = /%/g;
|
||||
function injectQuery(url, importer, queryToInject) {
|
||||
const { search, hash } = new URL(url.replace(replacePercentageRE, "%25"), importer);
|
||||
return `${cleanUrl(url)}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
|
||||
}
|
||||
let __require;
|
||||
function getBuiltinModule(moduleId) {
|
||||
__require ??= module$1.createRequire(import.meta.url);
|
||||
return __require(`${moduleId}?mock=actual`);
|
||||
}
|
||||
function genSourceMapUrl(map) {
|
||||
if (typeof map !== "string") map = JSON.stringify(map);
|
||||
return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
|
||||
}
|
||||
function transformCode(code, format, filename) {
|
||||
if (format.includes("typescript")) {
|
||||
if (!module$1.stripTypeScriptTypes) throw new Error(`Cannot parse '${filename}' because "module.stripTypeScriptTypes" is not supported. Module mocking requires Node.js 22.15 or higher. This is NOT a bug of Vitest.`);
|
||||
return module$1.stripTypeScriptTypes(code);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export { NativeModuleMocker };
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "dateformat",
|
||||
"description": "A node.js package for Steven Levithan's excellent dateFormat() function.",
|
||||
"maintainers": [
|
||||
"Felix Geisendörfer <felix@debuggable.com>"
|
||||
],
|
||||
"homepage": "https://github.com/felixge/node-dateformat",
|
||||
"author": "Steven Levithan",
|
||||
"contributors": [
|
||||
"Steven Levithan",
|
||||
"Felix Geisendörfer <felix@debuggable.com>",
|
||||
"Christoph Tavan <dev@tavan.de>",
|
||||
"Jon Schlinkert (https://github.com/jonschlinkert)"
|
||||
],
|
||||
"version": "4.6.3",
|
||||
"license": "MIT",
|
||||
"main": "lib/dateformat",
|
||||
"devDependencies": {
|
||||
"@babel/cli": "^7.12.10",
|
||||
"@babel/core": "^7.12.10",
|
||||
"@babel/preset-env": "^7.12.11",
|
||||
"mocha": "^8.2.1",
|
||||
"uglify-js": "^3.12.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "./node_modules/.bin/babel src --out-dir lib && uglifyjs lib/dateformat.js -o lib/dateformat.js",
|
||||
"test": "npm run build && mocha",
|
||||
"benchmark": "npm run build && node ./benchmark/benchmark.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/felixge/node-dateformat.git"
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
import * as core from "../core/index.cjs";
|
||||
import * as util from "../core/util.cjs";
|
||||
type SomeType = core.SomeType;
|
||||
export interface ZodMiniType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
|
||||
type: Internals["def"]["type"];
|
||||
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
|
||||
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
|
||||
clone(def?: Internals["def"], params?: {
|
||||
parent: boolean;
|
||||
}): this;
|
||||
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
|
||||
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
|
||||
def: Internals["def"];
|
||||
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
|
||||
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): util.SafeParseResult<core.output<this>>;
|
||||
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
|
||||
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<util.SafeParseResult<core.output<this>>>;
|
||||
apply<T>(fn: (schema: this) => T): T;
|
||||
}
|
||||
interface _ZodMiniType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodMiniType<any, any, Internals> {
|
||||
}
|
||||
export declare const ZodMiniType: core.$constructor<ZodMiniType>;
|
||||
export interface _ZodMiniString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodMiniType<T>, core.$ZodString<T["input"]> {
|
||||
_zod: T;
|
||||
}
|
||||
export interface ZodMiniString<Input = unknown> extends _ZodMiniString<core.$ZodStringInternals<Input>>, core.$ZodString<Input> {
|
||||
}
|
||||
export declare const ZodMiniString: core.$constructor<ZodMiniString>;
|
||||
export declare function string(params?: string | core.$ZodStringParams): ZodMiniString<string>;
|
||||
export interface ZodMiniStringFormat<Format extends string = string> extends _ZodMiniString<core.$ZodStringFormatInternals<Format>>, core.$ZodStringFormat<Format> {
|
||||
}
|
||||
export declare const ZodMiniStringFormat: core.$constructor<ZodMiniStringFormat>;
|
||||
export interface ZodMiniEmail extends _ZodMiniString<core.$ZodEmailInternals> {
|
||||
}
|
||||
export declare const ZodMiniEmail: core.$constructor<ZodMiniEmail>;
|
||||
export declare function email(params?: string | core.$ZodEmailParams): ZodMiniEmail;
|
||||
export interface ZodMiniGUID extends _ZodMiniString<core.$ZodGUIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniGUID: core.$constructor<ZodMiniGUID>;
|
||||
export declare function guid(params?: string | core.$ZodGUIDParams): ZodMiniGUID;
|
||||
export interface ZodMiniUUID extends _ZodMiniString<core.$ZodUUIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniUUID: core.$constructor<ZodMiniUUID>;
|
||||
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodMiniUUID;
|
||||
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodMiniUUID;
|
||||
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodMiniUUID;
|
||||
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodMiniUUID;
|
||||
export interface ZodMiniURL extends _ZodMiniString<core.$ZodURLInternals> {
|
||||
}
|
||||
export declare const ZodMiniURL: core.$constructor<ZodMiniURL>;
|
||||
export declare function url(params?: string | core.$ZodURLParams): ZodMiniURL;
|
||||
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodMiniURL;
|
||||
export interface ZodMiniEmoji extends _ZodMiniString<core.$ZodEmojiInternals> {
|
||||
}
|
||||
export declare const ZodMiniEmoji: core.$constructor<ZodMiniEmoji>;
|
||||
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodMiniEmoji;
|
||||
export interface ZodMiniNanoID extends _ZodMiniString<core.$ZodNanoIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniNanoID: core.$constructor<ZodMiniNanoID>;
|
||||
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodMiniNanoID;
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export interface ZodMiniCUID extends _ZodMiniString<core.$ZodCUIDInternals> {
|
||||
}
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export declare const ZodMiniCUID: core.$constructor<ZodMiniCUID>;
|
||||
/**
|
||||
* Validates a CUID v1 string.
|
||||
*
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodMiniCUID;
|
||||
export interface ZodMiniCUID2 extends _ZodMiniString<core.$ZodCUID2Internals> {
|
||||
}
|
||||
export declare const ZodMiniCUID2: core.$constructor<ZodMiniCUID2>;
|
||||
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodMiniCUID2;
|
||||
export interface ZodMiniULID extends _ZodMiniString<core.$ZodULIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniULID: core.$constructor<ZodMiniULID>;
|
||||
export declare function ulid(params?: string | core.$ZodULIDParams): ZodMiniULID;
|
||||
export interface ZodMiniXID extends _ZodMiniString<core.$ZodXIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniXID: core.$constructor<ZodMiniXID>;
|
||||
export declare function xid(params?: string | core.$ZodXIDParams): ZodMiniXID;
|
||||
export interface ZodMiniKSUID extends _ZodMiniString<core.$ZodKSUIDInternals> {
|
||||
}
|
||||
export declare const ZodMiniKSUID: core.$constructor<ZodMiniKSUID>;
|
||||
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodMiniKSUID;
|
||||
export interface ZodMiniIPv4 extends _ZodMiniString<core.$ZodIPv4Internals> {
|
||||
}
|
||||
export declare const ZodMiniIPv4: core.$constructor<ZodMiniIPv4>;
|
||||
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodMiniIPv4;
|
||||
export interface ZodMiniIPv6 extends _ZodMiniString<core.$ZodIPv6Internals> {
|
||||
}
|
||||
export declare const ZodMiniIPv6: core.$constructor<ZodMiniIPv6>;
|
||||
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodMiniIPv6;
|
||||
export interface ZodMiniCIDRv4 extends _ZodMiniString<core.$ZodCIDRv4Internals> {
|
||||
}
|
||||
export declare const ZodMiniCIDRv4: core.$constructor<ZodMiniCIDRv4>;
|
||||
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodMiniCIDRv4;
|
||||
export interface ZodMiniCIDRv6 extends _ZodMiniString<core.$ZodCIDRv6Internals> {
|
||||
}
|
||||
export declare const ZodMiniCIDRv6: core.$constructor<ZodMiniCIDRv6>;
|
||||
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodMiniCIDRv6;
|
||||
export interface ZodMiniMAC extends _ZodMiniString<core.$ZodMACInternals> {
|
||||
}
|
||||
export declare const ZodMiniMAC: core.$constructor<ZodMiniMAC>;
|
||||
export declare function mac(params?: string | core.$ZodMACParams): ZodMiniMAC;
|
||||
export interface ZodMiniBase64 extends _ZodMiniString<core.$ZodBase64Internals> {
|
||||
}
|
||||
export declare const ZodMiniBase64: core.$constructor<ZodMiniBase64>;
|
||||
export declare function base64(params?: string | core.$ZodBase64Params): ZodMiniBase64;
|
||||
export interface ZodMiniBase64URL extends _ZodMiniString<core.$ZodBase64URLInternals> {
|
||||
}
|
||||
export declare const ZodMiniBase64URL: core.$constructor<ZodMiniBase64URL>;
|
||||
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodMiniBase64URL;
|
||||
export interface ZodMiniE164 extends _ZodMiniString<core.$ZodE164Internals> {
|
||||
}
|
||||
export declare const ZodMiniE164: core.$constructor<ZodMiniE164>;
|
||||
export declare function e164(params?: string | core.$ZodE164Params): ZodMiniE164;
|
||||
export interface ZodMiniJWT extends _ZodMiniString<core.$ZodJWTInternals> {
|
||||
}
|
||||
export declare const ZodMiniJWT: core.$constructor<ZodMiniJWT>;
|
||||
export declare function jwt(params?: string | core.$ZodJWTParams): ZodMiniJWT;
|
||||
export interface ZodMiniCustomStringFormat<Format extends string = string> extends ZodMiniStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
|
||||
_zod: core.$ZodCustomStringFormatInternals<Format>;
|
||||
}
|
||||
export declare const ZodMiniCustomStringFormat: core.$constructor<ZodMiniCustomStringFormat>;
|
||||
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodMiniCustomStringFormat<Format>;
|
||||
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodMiniCustomStringFormat<"hostname">;
|
||||
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodMiniCustomStringFormat<"hex">;
|
||||
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
|
||||
enc?: Enc;
|
||||
} & core.$ZodStringFormatParams): ZodMiniCustomStringFormat<`${Alg}_${Enc}`>;
|
||||
interface _ZodMiniNumber<T extends core.$ZodNumberInternals<unknown> = core.$ZodNumberInternals<unknown>> extends _ZodMiniType<T>, core.$ZodNumber<T["input"]> {
|
||||
_zod: T;
|
||||
}
|
||||
export interface ZodMiniNumber<Input = unknown> extends _ZodMiniNumber<core.$ZodNumberInternals<Input>>, core.$ZodNumber<Input> {
|
||||
}
|
||||
export declare const ZodMiniNumber: core.$constructor<ZodMiniNumber>;
|
||||
export declare function number(params?: string | core.$ZodNumberParams): ZodMiniNumber<number>;
|
||||
export interface ZodMiniNumberFormat extends _ZodMiniNumber<core.$ZodNumberFormatInternals>, core.$ZodNumberFormat {
|
||||
}
|
||||
export declare const ZodMiniNumberFormat: core.$constructor<ZodMiniNumberFormat>;
|
||||
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodMiniNumberFormat;
|
||||
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodMiniNumberFormat;
|
||||
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodMiniNumberFormat;
|
||||
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodMiniNumberFormat;
|
||||
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodMiniNumberFormat;
|
||||
export interface ZodMiniBoolean<T = unknown> extends _ZodMiniType<core.$ZodBooleanInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniBoolean: core.$constructor<ZodMiniBoolean>;
|
||||
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodMiniBoolean<boolean>;
|
||||
export interface ZodMiniBigInt<T = unknown> extends _ZodMiniType<core.$ZodBigIntInternals<T>>, core.$ZodBigInt<T> {
|
||||
}
|
||||
export declare const ZodMiniBigInt: core.$constructor<ZodMiniBigInt>;
|
||||
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodMiniBigInt<bigint>;
|
||||
export interface ZodMiniBigIntFormat extends _ZodMiniType<core.$ZodBigIntFormatInternals> {
|
||||
}
|
||||
export declare const ZodMiniBigIntFormat: core.$constructor<ZodMiniBigIntFormat>;
|
||||
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodMiniBigIntFormat;
|
||||
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodMiniBigIntFormat;
|
||||
export interface ZodMiniSymbol extends _ZodMiniType<core.$ZodSymbolInternals> {
|
||||
}
|
||||
export declare const ZodMiniSymbol: core.$constructor<ZodMiniSymbol>;
|
||||
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodMiniSymbol;
|
||||
export interface ZodMiniUndefined extends _ZodMiniType<core.$ZodUndefinedInternals> {
|
||||
}
|
||||
export declare const ZodMiniUndefined: core.$constructor<ZodMiniUndefined>;
|
||||
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodMiniUndefined;
|
||||
export { _undefined as undefined };
|
||||
export interface ZodMiniNull extends _ZodMiniType<core.$ZodNullInternals> {
|
||||
}
|
||||
export declare const ZodMiniNull: core.$constructor<ZodMiniNull>;
|
||||
declare function _null(params?: string | core.$ZodNullParams): ZodMiniNull;
|
||||
export { _null as null };
|
||||
export interface ZodMiniAny extends _ZodMiniType<core.$ZodAnyInternals> {
|
||||
}
|
||||
export declare const ZodMiniAny: core.$constructor<ZodMiniAny>;
|
||||
export declare function any(): ZodMiniAny;
|
||||
export interface ZodMiniUnknown extends _ZodMiniType<core.$ZodUnknownInternals> {
|
||||
}
|
||||
export declare const ZodMiniUnknown: core.$constructor<ZodMiniUnknown>;
|
||||
export declare function unknown(): ZodMiniUnknown;
|
||||
export interface ZodMiniNever extends _ZodMiniType<core.$ZodNeverInternals> {
|
||||
}
|
||||
export declare const ZodMiniNever: core.$constructor<ZodMiniNever>;
|
||||
export declare function never(params?: string | core.$ZodNeverParams): ZodMiniNever;
|
||||
export interface ZodMiniVoid extends _ZodMiniType<core.$ZodVoidInternals> {
|
||||
}
|
||||
export declare const ZodMiniVoid: core.$constructor<ZodMiniVoid>;
|
||||
declare function _void(params?: string | core.$ZodVoidParams): ZodMiniVoid;
|
||||
export { _void as void };
|
||||
export interface ZodMiniDate<T = unknown> extends _ZodMiniType<core.$ZodDateInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniDate: core.$constructor<ZodMiniDate>;
|
||||
export declare function date(params?: string | core.$ZodDateParams): ZodMiniDate<Date>;
|
||||
export interface ZodMiniArray<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
|
||||
}
|
||||
export declare const ZodMiniArray: core.$constructor<ZodMiniArray>;
|
||||
export declare function array<T extends SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodMiniArray<T>;
|
||||
export declare function keyof<T extends ZodMiniObject>(schema: T): ZodMiniEnum<util.KeysEnum<T["shape"]>>;
|
||||
export interface ZodMiniObject<
|
||||
/** @ts-ignore Cast variance */
|
||||
out Shape extends core.$ZodShape = core.$ZodShape, out Config extends core.$ZodObjectConfig = core.$strip> extends ZodMiniType<any, any, core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
|
||||
shape: Shape;
|
||||
}
|
||||
export declare const ZodMiniObject: core.$constructor<ZodMiniObject>;
|
||||
export declare function object<T extends core.$ZodLooseShape = Record<never, SomeType>>(shape?: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strip>;
|
||||
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strict>;
|
||||
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$loose>;
|
||||
export declare function extend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: U): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
|
||||
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
|
||||
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
|
||||
};
|
||||
export declare function safeExtend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: SafeExtendShape<T["shape"], U>): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
|
||||
/** @deprecated Identical to `z.extend(A, B)` */
|
||||
export declare function merge<T extends ZodMiniObject, U extends ZodMiniObject>(a: T, b: U): ZodMiniObject<util.Extend<T["shape"], U["shape"]>, T["_zod"]["config"]>;
|
||||
export declare function pick<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Pick<T["shape"], keyof T["shape"] & keyof M>>, T["_zod"]["config"]>;
|
||||
export declare function omit<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Omit<T["shape"], keyof M>>, T["_zod"]["config"]>;
|
||||
export declare function partial<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
|
||||
-readonly [k in keyof T["shape"]]: ZodMiniOptional<T["shape"][k]>;
|
||||
}, T["_zod"]["config"]>;
|
||||
export declare function partial<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<{
|
||||
-readonly [k in keyof T["shape"]]: k extends keyof M ? ZodMiniOptional<T["shape"][k]> : T["shape"][k];
|
||||
}, T["_zod"]["config"]>;
|
||||
export type RequiredInterfaceShape<Shape extends core.$ZodLooseShape, Keys extends PropertyKey = keyof Shape> = util.Identity<{
|
||||
[k in keyof Shape as k extends Keys ? k : never]: ZodMiniNonOptional<Shape[k]>;
|
||||
} & {
|
||||
[k in keyof Shape as k extends Keys ? never : k]: Shape[k];
|
||||
}>;
|
||||
export declare function required<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
|
||||
-readonly [k in keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
|
||||
}, T["_zod"]["config"]>;
|
||||
export declare function required<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Extend<T["shape"], {
|
||||
[k in keyof M & keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
|
||||
}>, T["_zod"]["config"]>;
|
||||
export declare function catchall<T extends ZodMiniObject, U extends SomeType>(inst: T, catchall: U): ZodMiniObject<T["shape"], core.$catchall<U>>;
|
||||
export interface ZodMiniUnion<T extends readonly SomeType[] = readonly core.$ZodType[]> extends _ZodMiniType<core.$ZodUnionInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniUnion: core.$constructor<ZodMiniUnion>;
|
||||
export declare function union<const T extends readonly SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodMiniUnion<T>;
|
||||
export interface ZodMiniXor<T extends readonly SomeType[] = readonly core.$ZodType[]> extends _ZodMiniType<core.$ZodXorInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniXor: core.$constructor<ZodMiniXor>;
|
||||
/** Creates an exclusive union (XOR) where exactly one option must match.
|
||||
* Unlike regular unions that succeed when any option matches, xor fails if
|
||||
* zero or more than one option matches the input. */
|
||||
export declare function xor<const T extends readonly SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodMiniXor<T>;
|
||||
export interface ZodMiniDiscriminatedUnion<Options extends readonly SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodMiniUnion<Options> {
|
||||
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
|
||||
}
|
||||
export declare const ZodMiniDiscriminatedUnion: core.$constructor<ZodMiniDiscriminatedUnion>;
|
||||
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodMiniDiscriminatedUnion<Types, Disc>;
|
||||
export interface ZodMiniIntersection<A extends SomeType = core.$ZodType, B extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodIntersectionInternals<A, B>> {
|
||||
}
|
||||
export declare const ZodMiniIntersection: core.$constructor<ZodMiniIntersection>;
|
||||
export declare function intersection<T extends SomeType, U extends SomeType>(left: T, right: U): ZodMiniIntersection<T, U>;
|
||||
export interface ZodMiniTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends SomeType | null = core.$ZodType | null> extends _ZodMiniType<core.$ZodTupleInternals<T, Rest>> {
|
||||
}
|
||||
export declare const ZodMiniTuple: core.$constructor<ZodMiniTuple>;
|
||||
export declare function tuple<const T extends readonly [SomeType, ...SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodMiniTuple<T, null>;
|
||||
export declare function tuple<const T extends readonly [SomeType, ...SomeType[]], Rest extends SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodMiniTuple<T, Rest>;
|
||||
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodMiniTuple<[], null>;
|
||||
export interface ZodMiniRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodRecordInternals<Key, Value>> {
|
||||
}
|
||||
export declare const ZodMiniRecord: core.$constructor<ZodMiniRecord>;
|
||||
export declare function record<Key extends core.$ZodRecordKey, Value extends SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodMiniRecord<Key, Value>;
|
||||
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodMiniRecord<Key & core.$partial, Value>;
|
||||
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodMiniRecord<Key, Value>;
|
||||
export interface ZodMiniMap<Key extends SomeType = core.$ZodType, Value extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodMapInternals<Key, Value>> {
|
||||
}
|
||||
export declare const ZodMiniMap: core.$constructor<ZodMiniMap>;
|
||||
export declare function map<Key extends SomeType, Value extends SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMiniMap<Key, Value>;
|
||||
export interface ZodMiniSet<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodSetInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniSet: core.$constructor<ZodMiniSet>;
|
||||
export declare function set<Value extends SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodMiniSet<Value>;
|
||||
export interface ZodMiniEnum<T extends util.EnumLike = util.EnumLike> extends _ZodMiniType<core.$ZodEnumInternals<T>> {
|
||||
options: Array<T[keyof T]>;
|
||||
}
|
||||
export declare const ZodMiniEnum: core.$constructor<ZodMiniEnum>;
|
||||
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodMiniEnum<util.ToEnum<T[number]>>;
|
||||
declare function _enum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodMiniEnum<T>;
|
||||
export { _enum as enum };
|
||||
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
|
||||
*
|
||||
* ```ts
|
||||
* enum Colors { red, green, blue }
|
||||
* z.enum(Colors);
|
||||
* ```
|
||||
*/
|
||||
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodMiniEnum<T>;
|
||||
export interface ZodMiniLiteral<T extends util.Literal = util.Literal> extends _ZodMiniType<core.$ZodLiteralInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniLiteral: core.$constructor<ZodMiniLiteral>;
|
||||
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodMiniLiteral<T[number]>;
|
||||
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodMiniLiteral<T>;
|
||||
export interface ZodMiniFile extends _ZodMiniType<core.$ZodFileInternals> {
|
||||
}
|
||||
export declare const ZodMiniFile: core.$constructor<ZodMiniFile>;
|
||||
export declare function file(params?: string | core.$ZodFileParams): ZodMiniFile;
|
||||
export interface ZodMiniTransform<O = unknown, I = unknown> extends _ZodMiniType<core.$ZodTransformInternals<O, I>> {
|
||||
}
|
||||
export declare const ZodMiniTransform: core.$constructor<ZodMiniTransform>;
|
||||
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.ParsePayload) => O): ZodMiniTransform<Awaited<O>, I>;
|
||||
export interface ZodMiniOptional<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
|
||||
}
|
||||
export declare const ZodMiniOptional: core.$constructor<ZodMiniOptional>;
|
||||
export declare function optional<T extends SomeType>(innerType: T): ZodMiniOptional<T>;
|
||||
export interface ZodMiniExactOptional<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
|
||||
}
|
||||
export declare const ZodMiniExactOptional: core.$constructor<ZodMiniExactOptional>;
|
||||
export declare function exactOptional<T extends SomeType>(innerType: T): ZodMiniExactOptional<T>;
|
||||
export interface ZodMiniNullable<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodNullableInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniNullable: core.$constructor<ZodMiniNullable>;
|
||||
export declare function nullable<T extends SomeType>(innerType: T): ZodMiniNullable<T>;
|
||||
export declare function nullish<T extends SomeType>(innerType: T): ZodMiniOptional<ZodMiniNullable<T>>;
|
||||
export interface ZodMiniDefault<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodDefaultInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniDefault: core.$constructor<ZodMiniDefault>;
|
||||
export declare function _default<T extends SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodMiniDefault<T>;
|
||||
export interface ZodMiniPrefault<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodPrefaultInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniPrefault: core.$constructor<ZodMiniPrefault>;
|
||||
export declare function prefault<T extends SomeType>(innerType: T, defaultValue: util.NoUndefined<core.input<T>> | (() => util.NoUndefined<core.input<T>>)): ZodMiniPrefault<T>;
|
||||
export interface ZodMiniNonOptional<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodNonOptionalInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniNonOptional: core.$constructor<ZodMiniNonOptional>;
|
||||
export declare function nonoptional<T extends SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodMiniNonOptional<T>;
|
||||
export interface ZodMiniSuccess<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodSuccessInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniSuccess: core.$constructor<ZodMiniSuccess>;
|
||||
export declare function success<T extends SomeType>(innerType: T): ZodMiniSuccess<T>;
|
||||
export interface ZodMiniCatch<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodCatchInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniCatch: core.$constructor<ZodMiniCatch>;
|
||||
declare function _catch<T extends SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodMiniCatch<T>;
|
||||
export { _catch as catch };
|
||||
export interface ZodMiniNaN extends _ZodMiniType<core.$ZodNaNInternals> {
|
||||
}
|
||||
export declare const ZodMiniNaN: core.$constructor<ZodMiniNaN>;
|
||||
export declare function nan(params?: string | core.$ZodNaNParams): ZodMiniNaN;
|
||||
export interface ZodMiniPipe<A extends SomeType = core.$ZodType, B extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodPipeInternals<A, B>> {
|
||||
}
|
||||
export declare const ZodMiniPipe: core.$constructor<ZodMiniPipe>;
|
||||
export declare function pipe<const A extends SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodMiniPipe<A, B>;
|
||||
export interface ZodMiniCodec<A extends SomeType = core.$ZodType, B extends SomeType = core.$ZodType> extends ZodMiniPipe<A, B>, core.$ZodCodec<A, B> {
|
||||
_zod: core.$ZodCodecInternals<A, B>;
|
||||
def: core.$ZodCodecDef<A, B>;
|
||||
}
|
||||
export declare const ZodMiniCodec: core.$constructor<ZodMiniCodec>;
|
||||
export declare function codec<const A extends SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
|
||||
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
|
||||
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
|
||||
}): ZodMiniCodec<A, B>;
|
||||
export declare function invertCodec<A extends SomeType, B extends SomeType>(codec: ZodMiniCodec<A, B>): ZodMiniCodec<B, A>;
|
||||
export interface ZodMiniReadonly<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodReadonlyInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniReadonly: core.$constructor<ZodMiniReadonly>;
|
||||
export declare function readonly<T extends SomeType>(innerType: T): ZodMiniReadonly<T>;
|
||||
export interface ZodMiniTemplateLiteral<Template extends string = string> extends _ZodMiniType<core.$ZodTemplateLiteralInternals<Template>> {
|
||||
}
|
||||
export declare const ZodMiniTemplateLiteral: core.$constructor<ZodMiniTemplateLiteral>;
|
||||
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodMiniTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
|
||||
export interface ZodMiniLazy<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodLazyInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniLazy: core.$constructor<ZodMiniLazy>;
|
||||
declare function _lazy<T extends SomeType>(getter: () => T): ZodMiniLazy<T>;
|
||||
export { _lazy as lazy };
|
||||
export interface ZodMiniPromise<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodPromiseInternals<T>> {
|
||||
}
|
||||
export declare const ZodMiniPromise: core.$constructor<ZodMiniPromise>;
|
||||
export declare function promise<T extends SomeType>(innerType: T): ZodMiniPromise<T>;
|
||||
export interface ZodMiniCustom<O = unknown, I = unknown> extends _ZodMiniType<core.$ZodCustomInternals<O, I>> {
|
||||
}
|
||||
export declare const ZodMiniCustom: core.$constructor<ZodMiniCustom>;
|
||||
export declare function check<O = unknown>(fn: core.CheckFn<O>, params?: string | core.$ZodCustomParams): core.$ZodCheck<O>;
|
||||
export declare function custom<O = unknown, I = O>(fn?: (data: O) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodMiniCustom<O, I>;
|
||||
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
|
||||
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
|
||||
export declare const describe: typeof core.describe;
|
||||
export declare const meta: typeof core.meta;
|
||||
declare abstract class Class {
|
||||
constructor(..._args: any[]);
|
||||
}
|
||||
declare function _instanceof<T extends typeof Class>(cls: T, params?: core.$ZodCustomParams): ZodMiniCustom<InstanceType<T>, InstanceType<T>>;
|
||||
export { _instanceof as instanceof };
|
||||
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodMiniCodec<ZodMiniString, ZodMiniBoolean>;
|
||||
export type _ZodMiniJSONSchema = ZodMiniUnion<[
|
||||
ZodMiniString,
|
||||
ZodMiniNumber,
|
||||
ZodMiniBoolean,
|
||||
ZodMiniNull,
|
||||
ZodMiniArray<ZodMiniJSONSchema>,
|
||||
ZodMiniRecord<ZodMiniString<string>, ZodMiniJSONSchema>
|
||||
]>;
|
||||
export type _ZodMiniJSONSchemaInternals = _ZodMiniJSONSchema["_zod"];
|
||||
export interface ZodMiniJSONSchemaInternals extends _ZodMiniJSONSchemaInternals {
|
||||
output: util.JSONType;
|
||||
input: util.JSONType;
|
||||
}
|
||||
export interface ZodMiniJSONSchema extends _ZodMiniJSONSchema {
|
||||
_zod: ZodMiniJSONSchemaInternals;
|
||||
}
|
||||
export declare function json(): ZodMiniJSONSchema;
|
||||
export interface ZodMiniFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodMiniType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
|
||||
_def: core.$ZodFunctionDef<Args, Returns>;
|
||||
_input: core.$InferInnerFunctionType<Args, Returns>;
|
||||
_output: core.$InferOuterFunctionType<Args, Returns>;
|
||||
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodMiniFunction<ZodMiniTuple<Items, Rest>, Returns>;
|
||||
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodMiniFunction<NewArgs, Returns>;
|
||||
input(...args: any[]): ZodMiniFunction<any, Returns>;
|
||||
output<NewReturns extends core.$ZodFunctionOut>(output: NewReturns): ZodMiniFunction<Args, NewReturns>;
|
||||
}
|
||||
export declare const ZodMiniFunction: core.$constructor<ZodMiniFunction>;
|
||||
export declare function _function(): ZodMiniFunction;
|
||||
export declare function _function<const In extends Array<SomeType> = Array<SomeType>>(params: {
|
||||
input: In;
|
||||
}): ZodMiniFunction<ZodMiniTuple<In, null>, core.$ZodFunctionOut>;
|
||||
export declare function _function<const In extends Array<SomeType> = Array<SomeType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
|
||||
input: In;
|
||||
output: Out;
|
||||
}): ZodMiniFunction<ZodMiniTuple<In, null>, Out>;
|
||||
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
|
||||
input: In;
|
||||
}): ZodMiniFunction<In, core.$ZodFunctionOut>;
|
||||
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
|
||||
output: Out;
|
||||
}): ZodMiniFunction<core.$ZodFunctionIn, Out>;
|
||||
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params?: {
|
||||
input: In;
|
||||
output: Out;
|
||||
}): ZodMiniFunction<In, Out>;
|
||||
export { _function as function };
|
||||
Reference in New Issue
Block a user