WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag adding properties to native object's prototypes.
|
||||
* @author David Nelson
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
defaultOptions: [{ exceptions: [] }],
|
||||
|
||||
docs: {
|
||||
description: "Disallow extending native types",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/no-extend-native",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
exceptions: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
uniqueItems: true,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpected:
|
||||
"{{builtin}} prototype is read only, properties should not be added.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
const exceptions = new Set(context.options[0].exceptions);
|
||||
const modifiedBuiltins = new Set(
|
||||
Object.keys(astUtils.ECMASCRIPT_GLOBALS)
|
||||
.filter(builtin => builtin[0].toUpperCase() === builtin[0])
|
||||
.filter(builtin => !exceptions.has(builtin)),
|
||||
);
|
||||
|
||||
/**
|
||||
* Reports a lint error for the given node.
|
||||
* @param {ASTNode} node The node to report.
|
||||
* @param {string} builtin The name of the native builtin being extended.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportNode(node, builtin) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpected",
|
||||
data: {
|
||||
builtin,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if the `prototype` property of the given object
|
||||
* identifier node is being accessed.
|
||||
* @param {ASTNode} identifierNode The Identifier representing the object
|
||||
* to check.
|
||||
* @returns {boolean} True if the identifier is the object of a
|
||||
* MemberExpression and its `prototype` property is being accessed,
|
||||
* false otherwise.
|
||||
*/
|
||||
function isPrototypePropertyAccessed(identifierNode) {
|
||||
return Boolean(
|
||||
identifierNode &&
|
||||
identifierNode.parent &&
|
||||
identifierNode.parent.type === "MemberExpression" &&
|
||||
identifierNode.parent.object === identifierNode &&
|
||||
astUtils.getStaticPropertyName(identifierNode.parent) ===
|
||||
"prototype",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if it's an assignment to the property of the given node.
|
||||
* Example: `*.prop = 0` // the `*` is the given node.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} True if an assignment to the property of the node.
|
||||
*/
|
||||
function isAssigningToPropertyOf(node) {
|
||||
return (
|
||||
node.parent.type === "MemberExpression" &&
|
||||
node.parent.object === node &&
|
||||
node.parent.parent.type === "AssignmentExpression" &&
|
||||
node.parent.parent.left === node.parent
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`.
|
||||
*/
|
||||
function isInDefinePropertyCall(node) {
|
||||
return (
|
||||
node.parent.type === "CallExpression" &&
|
||||
node.parent.arguments[0] === node &&
|
||||
astUtils.isSpecificMemberAccess(
|
||||
node.parent.callee,
|
||||
"Object",
|
||||
/^definePropert(?:y|ies)$/u,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if object prototype access is part of a prototype
|
||||
* extension. There are three ways a prototype can be extended:
|
||||
* 1. Assignment to prototype property (Object.prototype.foo = 1)
|
||||
* 2. Object.defineProperty()/Object.defineProperties() on a prototype
|
||||
* If prototype extension is detected, report the AssignmentExpression
|
||||
* or CallExpression node.
|
||||
* @param {ASTNode} identifierNode The Identifier representing the object
|
||||
* which prototype is being accessed and possibly extended.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkAndReportPrototypeExtension(identifierNode) {
|
||||
if (!isPrototypePropertyAccessed(identifierNode)) {
|
||||
return; // This is not `*.prototype` access.
|
||||
}
|
||||
|
||||
/*
|
||||
* `identifierNode.parent` is a MemberExpression `*.prototype`.
|
||||
* If it's an optional member access, it may be wrapped by a `ChainExpression` node.
|
||||
*/
|
||||
const prototypeNode =
|
||||
identifierNode.parent.parent.type === "ChainExpression"
|
||||
? identifierNode.parent.parent
|
||||
: identifierNode.parent;
|
||||
|
||||
if (isAssigningToPropertyOf(prototypeNode)) {
|
||||
// `*.prototype` -> MemberExpression -> AssignmentExpression
|
||||
reportNode(prototypeNode.parent.parent, identifierNode.name);
|
||||
} else if (isInDefinePropertyCall(prototypeNode)) {
|
||||
// `*.prototype` -> CallExpression
|
||||
reportNode(prototypeNode.parent, identifierNode.name);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"Program:exit"(node) {
|
||||
const globalScope = sourceCode.getScope(node);
|
||||
|
||||
modifiedBuiltins.forEach(builtin => {
|
||||
const builtinVar = globalScope.set.get(builtin);
|
||||
|
||||
if (builtinVar && builtinVar.references) {
|
||||
builtinVar.references
|
||||
.map(ref => ref.identifier)
|
||||
.forEach(checkAndReportPrototypeExtension);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,363 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
||||
typeof define === 'function' && define.amd ? define(factory) :
|
||||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EventEmitter3 = factory());
|
||||
})(this, (function () { 'use strict';
|
||||
|
||||
function getDefaultExportFromCjs (x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
||||
}
|
||||
|
||||
var eventemitter3 = {exports: {}};
|
||||
|
||||
var hasRequiredEventemitter3;
|
||||
|
||||
function requireEventemitter3 () {
|
||||
if (hasRequiredEventemitter3) return eventemitter3.exports;
|
||||
hasRequiredEventemitter3 = 1;
|
||||
(function (module) {
|
||||
|
||||
var has = Object.prototype.hasOwnProperty
|
||||
, prefix = '~';
|
||||
|
||||
/**
|
||||
* Constructor to create a storage for our `EE` objects.
|
||||
* An `Events` instance is a plain object whose properties are event names.
|
||||
*
|
||||
* @constructor
|
||||
* @private
|
||||
*/
|
||||
function Events() {}
|
||||
|
||||
//
|
||||
// We try to not inherit from `Object.prototype`. In some engines creating an
|
||||
// instance in this way is faster than calling `Object.create(null)` directly.
|
||||
// If `Object.create(null)` is not supported we prefix the event names with a
|
||||
// character to make sure that the built-in object properties are not
|
||||
// overridden or used as an attack vector.
|
||||
//
|
||||
if (Object.create) {
|
||||
Events.prototype = Object.create(null);
|
||||
|
||||
//
|
||||
// This hack is needed because the `__proto__` property is still inherited in
|
||||
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
|
||||
//
|
||||
if (!new Events().__proto__) prefix = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Representation of a single event listener.
|
||||
*
|
||||
* @param {Function} fn The listener function.
|
||||
* @param {*} context The context to invoke the listener with.
|
||||
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
|
||||
* @constructor
|
||||
* @private
|
||||
*/
|
||||
function EE(fn, context, once) {
|
||||
this.fn = fn;
|
||||
this.context = context;
|
||||
this.once = once || false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a listener for a given event.
|
||||
*
|
||||
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @param {Function} fn The listener function.
|
||||
* @param {*} context The context to invoke the listener with.
|
||||
* @param {Boolean} once Specify if the listener is a one-time listener.
|
||||
* @returns {EventEmitter}
|
||||
* @private
|
||||
*/
|
||||
function addListener(emitter, event, fn, context, once) {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('The listener must be a function');
|
||||
}
|
||||
|
||||
var listener = new EE(fn, context || emitter, once)
|
||||
, evt = prefix ? prefix + event : event;
|
||||
|
||||
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
|
||||
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
|
||||
else emitter._events[evt] = [emitter._events[evt], listener];
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear event by name.
|
||||
*
|
||||
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
|
||||
* @param {(String|Symbol)} evt The Event name.
|
||||
* @private
|
||||
*/
|
||||
function clearEvent(emitter, evt) {
|
||||
if (--emitter._eventsCount === 0) emitter._events = new Events();
|
||||
else delete emitter._events[evt];
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal `EventEmitter` interface that is molded against the Node.js
|
||||
* `EventEmitter` interface.
|
||||
*
|
||||
* @constructor
|
||||
* @public
|
||||
*/
|
||||
function EventEmitter() {
|
||||
this._events = new Events();
|
||||
this._eventsCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an array listing the events for which the emitter has registered
|
||||
* listeners.
|
||||
*
|
||||
* @returns {Array}
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.eventNames = function eventNames() {
|
||||
var names = []
|
||||
, events
|
||||
, name;
|
||||
|
||||
if (this._eventsCount === 0) return names;
|
||||
|
||||
for (name in (events = this._events)) {
|
||||
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
|
||||
}
|
||||
|
||||
if (Object.getOwnPropertySymbols) {
|
||||
return names.concat(Object.getOwnPropertySymbols(events));
|
||||
}
|
||||
|
||||
return names;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the listeners registered for a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @returns {Array} The registered listeners.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.listeners = function listeners(event) {
|
||||
var evt = prefix ? prefix + event : event
|
||||
, handlers = this._events[evt];
|
||||
|
||||
if (!handlers) return [];
|
||||
if (handlers.fn) return [handlers.fn];
|
||||
|
||||
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
|
||||
ee[i] = handlers[i].fn;
|
||||
}
|
||||
|
||||
return ee;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the number of listeners listening to a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @returns {Number} The number of listeners.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.listenerCount = function listenerCount(event) {
|
||||
var evt = prefix ? prefix + event : event
|
||||
, listeners = this._events[evt];
|
||||
|
||||
if (!listeners) return 0;
|
||||
if (listeners.fn) return 1;
|
||||
return listeners.length;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calls each of the listeners registered for a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @returns {Boolean} `true` if the event had listeners, else `false`.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
|
||||
var evt = prefix ? prefix + event : event;
|
||||
|
||||
if (!this._events[evt]) return false;
|
||||
|
||||
var listeners = this._events[evt]
|
||||
, len = arguments.length
|
||||
, args
|
||||
, i;
|
||||
|
||||
if (listeners.fn) {
|
||||
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
|
||||
|
||||
switch (len) {
|
||||
case 1: return listeners.fn.call(listeners.context), true;
|
||||
case 2: return listeners.fn.call(listeners.context, a1), true;
|
||||
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
|
||||
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
|
||||
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
|
||||
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
|
||||
}
|
||||
|
||||
for (i = 1, args = new Array(len -1); i < len; i++) {
|
||||
args[i - 1] = arguments[i];
|
||||
}
|
||||
|
||||
listeners.fn.apply(listeners.context, args);
|
||||
} else {
|
||||
var length = listeners.length
|
||||
, j;
|
||||
|
||||
for (i = 0; i < length; i++) {
|
||||
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
|
||||
|
||||
switch (len) {
|
||||
case 1: listeners[i].fn.call(listeners[i].context); break;
|
||||
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
|
||||
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
|
||||
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
|
||||
default:
|
||||
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
|
||||
args[j - 1] = arguments[j];
|
||||
}
|
||||
|
||||
listeners[i].fn.apply(listeners[i].context, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a listener for a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @param {Function} fn The listener function.
|
||||
* @param {*} [context=this] The context to invoke the listener with.
|
||||
* @returns {EventEmitter} `this`.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.on = function on(event, fn, context) {
|
||||
return addListener(this, event, fn, context, false);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a one-time listener for a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @param {Function} fn The listener function.
|
||||
* @param {*} [context=this] The context to invoke the listener with.
|
||||
* @returns {EventEmitter} `this`.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.once = function once(event, fn, context) {
|
||||
return addListener(this, event, fn, context, true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove the listeners of a given event.
|
||||
*
|
||||
* @param {(String|Symbol)} event The event name.
|
||||
* @param {Function} fn Only remove the listeners that match this function.
|
||||
* @param {*} context Only remove the listeners that have this context.
|
||||
* @param {Boolean} once Only remove one-time listeners.
|
||||
* @returns {EventEmitter} `this`.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
|
||||
var evt = prefix ? prefix + event : event;
|
||||
|
||||
if (!this._events[evt]) return this;
|
||||
if (!fn) {
|
||||
clearEvent(this, evt);
|
||||
return this;
|
||||
}
|
||||
|
||||
var listeners = this._events[evt];
|
||||
|
||||
if (listeners.fn) {
|
||||
if (
|
||||
listeners.fn === fn &&
|
||||
(!once || listeners.once) &&
|
||||
(!context || listeners.context === context)
|
||||
) {
|
||||
clearEvent(this, evt);
|
||||
}
|
||||
} else {
|
||||
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
|
||||
if (
|
||||
listeners[i].fn !== fn ||
|
||||
(once && !listeners[i].once) ||
|
||||
(context && listeners[i].context !== context)
|
||||
) {
|
||||
events.push(listeners[i]);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Reset the array, or remove it completely if we have no more listeners.
|
||||
//
|
||||
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
|
||||
else clearEvent(this, evt);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove all listeners, or those of the specified event.
|
||||
*
|
||||
* @param {(String|Symbol)} [event] The event name.
|
||||
* @returns {EventEmitter} `this`.
|
||||
* @public
|
||||
*/
|
||||
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
|
||||
var evt;
|
||||
|
||||
if (event) {
|
||||
evt = prefix ? prefix + event : event;
|
||||
if (this._events[evt]) clearEvent(this, evt);
|
||||
} else {
|
||||
this._events = new Events();
|
||||
this._eventsCount = 0;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
//
|
||||
// Alias methods names because people roll like that.
|
||||
//
|
||||
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
||||
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
|
||||
|
||||
//
|
||||
// Expose the prefix.
|
||||
//
|
||||
EventEmitter.prefixed = prefix;
|
||||
|
||||
//
|
||||
// Allow `EventEmitter` to be imported as module namespace.
|
||||
//
|
||||
EventEmitter.EventEmitter = EventEmitter;
|
||||
|
||||
//
|
||||
// Expose the module.
|
||||
//
|
||||
{
|
||||
module.exports = EventEmitter;
|
||||
}
|
||||
} (eventemitter3));
|
||||
return eventemitter3.exports;
|
||||
}
|
||||
|
||||
var eventemitter3Exports = requireEventemitter3();
|
||||
var index = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
|
||||
|
||||
return index;
|
||||
|
||||
}));
|
||||
@@ -0,0 +1,197 @@
|
||||
import { expect, test } from "vitest";
|
||||
import * as z from "zod/v4";
|
||||
|
||||
/**
|
||||
* Schema methods are exposed in a way that works when detached from the
|
||||
* schema instance — `const opt = schema.optional; opt()` must produce a
|
||||
* working `ZodOptional`, not a corrupt one. This pattern is used in real
|
||||
* code (e.g. `arr.map(schema.parse)`, `arr.map(schema.optional)`,
|
||||
* destructuring inside utility functions).
|
||||
*
|
||||
* This test caught a regression in colinhacks/zod#5870 where a memory
|
||||
* optimization moved methods to the prototype and made `this`-binding
|
||||
* required, silently breaking any detached usage.
|
||||
*/
|
||||
|
||||
const probeArgs: Record<string, unknown[]> = {
|
||||
// ZodType
|
||||
optional: [],
|
||||
exactOptional: [],
|
||||
nullable: [],
|
||||
nullish: [],
|
||||
array: [],
|
||||
describe: ["x"],
|
||||
brand: [],
|
||||
readonly: [],
|
||||
default: ["fallback"],
|
||||
catch: ["fallback"],
|
||||
// _ZodString
|
||||
min: [1],
|
||||
max: [10],
|
||||
length: [5],
|
||||
nonempty: [],
|
||||
trim: [],
|
||||
toLowerCase: [],
|
||||
toUpperCase: [],
|
||||
// ZodString format methods
|
||||
email: [],
|
||||
url: [],
|
||||
uuid: [],
|
||||
cuid: [],
|
||||
cuid2: [],
|
||||
ulid: [],
|
||||
base64: [],
|
||||
base64url: [],
|
||||
ipv4: [],
|
||||
ipv6: [],
|
||||
// ZodNumber
|
||||
int: [],
|
||||
positive: [],
|
||||
negative: [],
|
||||
finite: [],
|
||||
};
|
||||
|
||||
test("detached parse-family methods work without `this` binding", () => {
|
||||
const schema = z.string();
|
||||
const { parse, safeParse } = schema;
|
||||
|
||||
expect(parse("hello")).toBe("hello");
|
||||
expect(safeParse("hello").success).toBe(true);
|
||||
});
|
||||
|
||||
test("detached schema.optional() returns a working ZodOptional", () => {
|
||||
const schema = z.string();
|
||||
const opt = schema.optional;
|
||||
|
||||
const detached = opt();
|
||||
|
||||
expect(detached).toBeInstanceOf(z.ZodOptional);
|
||||
expect(detached.safeParse("hello").success).toBe(true);
|
||||
expect(detached.safeParse(undefined).success).toBe(true);
|
||||
expect(detached.safeParse(123).success).toBe(false);
|
||||
});
|
||||
|
||||
test("detached schema.nullable() returns a working ZodNullable", () => {
|
||||
const schema = z.string();
|
||||
const nul = schema.nullable;
|
||||
|
||||
const detached = nul();
|
||||
|
||||
expect(detached).toBeInstanceOf(z.ZodNullable);
|
||||
expect(detached.safeParse("hello").success).toBe(true);
|
||||
expect(detached.safeParse(null).success).toBe(true);
|
||||
expect(detached.safeParse(123).success).toBe(false);
|
||||
});
|
||||
|
||||
test("detached schema.array() returns a working ZodArray", () => {
|
||||
const schema = z.string();
|
||||
const arr = schema.array;
|
||||
|
||||
const detached = arr();
|
||||
|
||||
expect(detached).toBeInstanceOf(z.ZodArray);
|
||||
expect(detached.safeParse(["a", "b"]).success).toBe(true);
|
||||
expect(detached.safeParse([1, 2]).success).toBe(false);
|
||||
});
|
||||
|
||||
test("detached schema.describe() returns a described schema", () => {
|
||||
const schema = z.string();
|
||||
const describe = schema.describe;
|
||||
|
||||
const described = describe("hello world");
|
||||
|
||||
expect(described.description).toBe("hello world");
|
||||
});
|
||||
|
||||
test("detached refinement still validates", () => {
|
||||
const schema = z.string();
|
||||
const refine = schema.refine;
|
||||
|
||||
const refined = refine((s: string) => s.startsWith("x"), "must start with x");
|
||||
|
||||
expect(refined.safeParse("xhello").success).toBe(true);
|
||||
expect(refined.safeParse("hello").success).toBe(false);
|
||||
});
|
||||
|
||||
test("detached chained calls work — schema.optional then parse", () => {
|
||||
const schema = z.string();
|
||||
const opt = schema.optional;
|
||||
const optionalSchema = opt();
|
||||
const { parse } = optionalSchema;
|
||||
|
||||
expect(parse("hi")).toBe("hi");
|
||||
expect(parse(undefined)).toBe(undefined);
|
||||
});
|
||||
|
||||
test("detached parse can be called as a free function", () => {
|
||||
const schema = z.string();
|
||||
const parse = schema.parse;
|
||||
const inputs = ["a", "b", "c"];
|
||||
|
||||
const results = inputs.map((v) => parse(v));
|
||||
|
||||
expect(results).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
test("detached methods on z.number() work", () => {
|
||||
const schema = z.number();
|
||||
|
||||
const min = schema.min;
|
||||
const max = schema.max;
|
||||
const positive = schema.positive;
|
||||
|
||||
expect(min(5).safeParse(3).success).toBe(false);
|
||||
expect(max(5).safeParse(7).success).toBe(false);
|
||||
expect(positive().safeParse(-1).success).toBe(false);
|
||||
});
|
||||
|
||||
test("detached object methods work", () => {
|
||||
const schema = z.object({ a: z.string(), b: z.number() });
|
||||
|
||||
const pick = schema.pick;
|
||||
const omit = schema.omit;
|
||||
const partial = schema.partial;
|
||||
const extend = schema.extend;
|
||||
|
||||
expect(Object.keys(pick({ a: true })._zod.def.shape)).toEqual(["a"]);
|
||||
expect(Object.keys(omit({ a: true })._zod.def.shape)).toEqual(["b"]);
|
||||
expect(partial().safeParse({}).success).toBe(true);
|
||||
const extended = extend({ c: z.boolean() });
|
||||
expect(Object.keys(extended._zod.def.shape).sort()).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
// Sweep across many builder methods at once. If any of them break with the
|
||||
// `const m = schema.foo; m(...)` pattern, this test will report which.
|
||||
test("broad sweep: detaching builder methods does not throw or produce a corrupt schema", () => {
|
||||
const stringSchema = z.string();
|
||||
const numberSchema = z.number();
|
||||
|
||||
const broken: Array<{ method: string; reason: string }> = [];
|
||||
|
||||
for (const [methodName, args] of Object.entries(probeArgs)) {
|
||||
const target: any = methodName in stringSchema ? stringSchema : methodName in numberSchema ? numberSchema : null;
|
||||
if (!target) continue;
|
||||
|
||||
const detached = target[methodName] as Function | undefined;
|
||||
if (typeof detached !== "function") continue;
|
||||
|
||||
try {
|
||||
const result = detached(...args);
|
||||
// If the detached call returned a schema, sanity-check it parses
|
||||
// its base type. (e.g. `optional()` should accept its inner type.)
|
||||
if (result && typeof result === "object" && "_zod" in result && typeof (result as any).safeParse === "function") {
|
||||
const probeValue = target === stringSchema ? "x" : 1;
|
||||
const r = (result as any).safeParse(probeValue);
|
||||
// success or a clean failure are both fine — we only fail on throw or
|
||||
// on a schema with corrupt internal state (innerType undefined etc).
|
||||
if (r === undefined || (typeof r === "object" && !("success" in r))) {
|
||||
broken.push({ method: methodName, reason: "safeParse returned malformed result" });
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
broken.push({ method: methodName, reason: err?.message ?? String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
expect(broken).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* RIPEMD-160 legacy hash function.
|
||||
* https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
|
||||
* https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
|
||||
* @module
|
||||
* @deprecated
|
||||
*/
|
||||
import { RIPEMD160 as RIPEMD160n, ripemd160 as ripemd160n } from './legacy.ts';
|
||||
/** @deprecated Use import from `noble/hashes/legacy` module */
|
||||
export declare const RIPEMD160: typeof RIPEMD160n;
|
||||
/** @deprecated Use import from `noble/hashes/legacy` module */
|
||||
export declare const ripemd160: typeof ripemd160n;
|
||||
//# sourceMappingURL=ripemd160.d.ts.map
|
||||
@@ -0,0 +1,3 @@
|
||||
# `@rolldown/binding-linux-x64-gnu`
|
||||
|
||||
This is the **x86_64-unknown-linux-gnu** binary for `@rolldown/binding`
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Client-side collection of per-request timing and transfer measurements.
|
||||
*
|
||||
* When enabled, each request records its round-trip latency and the number of
|
||||
* payload bytes sent and received, accumulated into running totals and a
|
||||
* fixed-size ring buffer of the most recent requests.
|
||||
*
|
||||
* The server measures its own per-request processing time independently. When a
|
||||
* timing snapshot is requested, the client fetches the server's collection via
|
||||
* a `getServerTiming` request and folds it into the returned {@link TimingInfo},
|
||||
* yielding per-request and total server processing time and an estimated
|
||||
* transport overhead (round-trip minus server processing time). Normal response
|
||||
* messages are left unchanged.
|
||||
*/
|
||||
/** Number of most-recent requests retained in the ring buffer. */
|
||||
export declare const RECENT_REQUEST_CAPACITY = 5;
|
||||
/** A single request's measured timing and transfer sample. */
|
||||
export interface RequestTiming {
|
||||
/** The API method that was invoked. */
|
||||
method: string;
|
||||
/** Wall-clock round-trip time measured by the client, in milliseconds. */
|
||||
roundTripMs: number;
|
||||
/** Number of request payload bytes sent to the server. */
|
||||
bytesSent: number;
|
||||
/** Number of response payload bytes received from the server. */
|
||||
bytesReceived: number;
|
||||
/** Wall-clock timestamp ({@link Date.now}) captured when the request completed. */
|
||||
timestamp: number;
|
||||
/**
|
||||
* Server-side processing time for this request, in milliseconds, as folded
|
||||
* in from the server's own timing collection. Undefined when server timing
|
||||
* for the request could not be matched.
|
||||
*/
|
||||
serverTimeMs?: number;
|
||||
/**
|
||||
* Estimated transport overhead for this request, in milliseconds
|
||||
* (`roundTripMs - serverTimeMs`, clamped to be non-negative). Present
|
||||
* exactly when {@link serverTimeMs} is.
|
||||
*/
|
||||
transportOverheadMs?: number;
|
||||
}
|
||||
/** Running totals accumulated across every measured request. */
|
||||
export interface TimingAccumulators {
|
||||
/** Number of requests measured. */
|
||||
requestCount: number;
|
||||
/** Sum of round-trip latencies, in milliseconds. */
|
||||
roundTripMs: number;
|
||||
/** Sum of request payload bytes sent. */
|
||||
bytesSent: number;
|
||||
/** Sum of response payload bytes received. */
|
||||
bytesReceived: number;
|
||||
/** Sum of server-side processing time, in milliseconds. */
|
||||
serverTimeMs: number;
|
||||
/**
|
||||
* Estimated total transport overhead, in milliseconds
|
||||
* (`roundTripMs - serverTimeMs`, clamped to be non-negative).
|
||||
*/
|
||||
transportOverheadMs: number;
|
||||
/**
|
||||
* Number of AST nodes materialized from binary source-file responses as the
|
||||
* client walked the returned trees. Materialization is lazy and happens on
|
||||
* demand, so this accrues after the originating request completes.
|
||||
*/
|
||||
nodesMaterialized: number;
|
||||
/**
|
||||
* Number of source files fetched from the server (each decoded into a
|
||||
* lazily-materialized tree).
|
||||
*/
|
||||
sourceFilesFetched: number;
|
||||
/**
|
||||
* Number of AST nodes across all fetched source files that can be
|
||||
* materialized on demand. Each fetched file contributes its full node count
|
||||
* (excluding the pre-materialized source-file node), whether or not those
|
||||
* nodes are ever walked. Serves as the denominator for the share of fetched
|
||||
* nodes that end up materialized (`nodesMaterialized / nodesFetched`).
|
||||
*/
|
||||
nodesFetched: number;
|
||||
}
|
||||
/** A point-in-time snapshot of collected timing information. */
|
||||
export interface TimingInfo {
|
||||
/** Whether timing collection is enabled for this API instance. */
|
||||
enabled: boolean;
|
||||
/** Running totals across every measured request. */
|
||||
totals: TimingAccumulators;
|
||||
/**
|
||||
* The most recent requests, up to {@link RECENT_REQUEST_CAPACITY}, ordered
|
||||
* from oldest to newest.
|
||||
*/
|
||||
recentRequests: RequestTiming[];
|
||||
}
|
||||
/** A raw measurement handed to {@link TimingCollector.record}. */
|
||||
export interface TimingSample {
|
||||
method: string;
|
||||
roundTripMs: number;
|
||||
bytesSent: number;
|
||||
bytesReceived: number;
|
||||
}
|
||||
/**
|
||||
* A single server-side request's processing-time sample, as returned by a
|
||||
* `getServerTiming` request. This is an internal wire shape; consumers see the
|
||||
* folded-in {@link RequestTiming.serverTimeMs}.
|
||||
*/
|
||||
export interface ServerRequestTiming {
|
||||
/** The API method that was handled. */
|
||||
method: string;
|
||||
/** Server-side processing time, in milliseconds. */
|
||||
processingTimeMs: number;
|
||||
/** Unix timestamp in milliseconds captured when the request completed. */
|
||||
timestamp: number;
|
||||
}
|
||||
/** Running totals accumulated on the server across every handled request. */
|
||||
export interface ServerTimingTotals {
|
||||
/** Total number of requests handled. */
|
||||
requestCount: number;
|
||||
/** Sum of server-side processing time, in milliseconds. */
|
||||
totalProcessingTimeMs: number;
|
||||
}
|
||||
/**
|
||||
* A snapshot of the server's own timing collection, retrieved via a
|
||||
* `getServerTiming` request. This is an internal wire shape used to compute the
|
||||
* server-derived fields of {@link TimingInfo}.
|
||||
*/
|
||||
export interface ServerTimingInfo {
|
||||
/** Whether server-side timing collection is enabled. */
|
||||
enabled: boolean;
|
||||
/** Running totals across every request the server handled. */
|
||||
totals: ServerTimingTotals;
|
||||
/**
|
||||
* The most recent requests as seen by the server, ordered from oldest to
|
||||
* newest.
|
||||
*/
|
||||
recentRequests: ServerRequestTiming[];
|
||||
}
|
||||
/** Returns a snapshot representing a disabled (never-collecting) timing state. */
|
||||
export declare function disabledTimingInfo(): TimingInfo;
|
||||
/** Returns a snapshot representing disabled server-side timing collection. */
|
||||
export declare function disabledServerTimingInfo(): ServerTimingInfo;
|
||||
/**
|
||||
* Folds a server-side timing snapshot into a client-side snapshot, producing a
|
||||
* combined {@link TimingInfo} with per-request and total server processing time
|
||||
* plus estimated transport overhead.
|
||||
*
|
||||
* Recent requests are paired newest-to-newest and only matched when the method
|
||||
* names agree, so that requests recorded by only one side (e.g. the meta
|
||||
* requests used to fetch timing) do not misalign the two ring buffers.
|
||||
*/
|
||||
export declare function combineTimingInfo(client: TimingInfo, server: ServerTimingInfo): TimingInfo;
|
||||
/**
|
||||
* Accumulates request timing samples into running totals and a fixed-size ring
|
||||
* buffer of the most recent requests.
|
||||
*/
|
||||
export declare class TimingCollector {
|
||||
private totals;
|
||||
private ring;
|
||||
private head;
|
||||
/** Records a single request's measurements. */
|
||||
record(sample: TimingSample): void;
|
||||
/**
|
||||
* Records a single AST node materialization. Called on demand as the consumer
|
||||
* walks a binary source-file response's tree, so it is not tied to any one
|
||||
* request.
|
||||
*/
|
||||
recordMaterialization(): void;
|
||||
/**
|
||||
* Records a fetched source file: increments the fetched-file counter and adds
|
||||
* the file's materializable node count to the fetched-node total, which serves
|
||||
* as the denominator for the share of fetched nodes that end up materialized.
|
||||
*/
|
||||
recordSourceFileFetched(materializableNodeCount: number): void;
|
||||
/** Returns a snapshot of the collected timing information. */
|
||||
getInfo(): TimingInfo;
|
||||
/** Clears all accumulated totals and recent-request history. */
|
||||
reset(): void;
|
||||
}
|
||||
//# sourceMappingURL=timing.d.ts.map
|
||||
@@ -0,0 +1,27 @@
|
||||
// @ts-ignore TS6133
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import * as z from "zod/v3";
|
||||
const stringSchema = z.string();
|
||||
|
||||
test("safeparse fail", () => {
|
||||
const safe = stringSchema.safeParse(12);
|
||||
expect(safe.success).toEqual(false);
|
||||
expect(safe.error).toBeInstanceOf(z.ZodError);
|
||||
});
|
||||
|
||||
test("safeparse pass", () => {
|
||||
const safe = stringSchema.safeParse("12");
|
||||
expect(safe.success).toEqual(true);
|
||||
expect(safe.data).toEqual("12");
|
||||
});
|
||||
|
||||
test("safeparse unexpected error", () => {
|
||||
expect(() =>
|
||||
stringSchema
|
||||
.refine((data) => {
|
||||
throw new Error(data);
|
||||
})
|
||||
.safeParse("12")
|
||||
).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
CommonClient,
|
||||
ICommonWebSocket,
|
||||
IWSClientAdditionalOptions,
|
||||
NodeWebSocketType,
|
||||
NodeWebSocketTypeOptions,
|
||||
WebSocket as createRpc,
|
||||
} from 'rpc-websockets';
|
||||
|
||||
interface IHasReadyState {
|
||||
readyState: WebSocket['readyState'];
|
||||
}
|
||||
|
||||
export default class RpcWebSocketClient extends CommonClient {
|
||||
private underlyingSocket: IHasReadyState | undefined;
|
||||
constructor(
|
||||
address?: string,
|
||||
options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,
|
||||
generate_request_id?: (
|
||||
method: string,
|
||||
params: object | Array<any>,
|
||||
) => number,
|
||||
) {
|
||||
const webSocketFactory = (url: string) => {
|
||||
const rpc = createRpc(url, {
|
||||
autoconnect: true,
|
||||
max_reconnects: 5,
|
||||
reconnect: true,
|
||||
reconnect_interval: 1000,
|
||||
...options,
|
||||
});
|
||||
if ('socket' in rpc) {
|
||||
this.underlyingSocket = rpc.socket as ReturnType<typeof createRpc>;
|
||||
} else {
|
||||
this.underlyingSocket = rpc as NodeWebSocketType;
|
||||
}
|
||||
return rpc as ICommonWebSocket;
|
||||
};
|
||||
super(webSocketFactory, address, options, generate_request_id);
|
||||
}
|
||||
call(
|
||||
...args: Parameters<CommonClient['call']>
|
||||
): ReturnType<CommonClient['call']> {
|
||||
const readyState = this.underlyingSocket?.readyState;
|
||||
if (readyState === 1 /* WebSocket.OPEN */) {
|
||||
return super.call(...args);
|
||||
}
|
||||
return Promise.reject(
|
||||
new Error(
|
||||
'Tried to call a JSON-RPC method `' +
|
||||
args[0] +
|
||||
'` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +
|
||||
readyState +
|
||||
')',
|
||||
),
|
||||
);
|
||||
}
|
||||
notify(
|
||||
...args: Parameters<CommonClient['notify']>
|
||||
): ReturnType<CommonClient['notify']> {
|
||||
const readyState = this.underlyingSocket?.readyState;
|
||||
if (readyState === 1 /* WebSocket.OPEN */) {
|
||||
return super.notify(...args);
|
||||
}
|
||||
return Promise.reject(
|
||||
new Error(
|
||||
'Tried to send a JSON-RPC notification `' +
|
||||
args[0] +
|
||||
'` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +
|
||||
readyState +
|
||||
')',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ExpiringCache = exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = void 0;
|
||||
exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = 30;
|
||||
const ZERO_HR_TIME = [0, 0];
|
||||
/**
|
||||
* A map with key-level expiration.
|
||||
*/
|
||||
class ExpiringCache {
|
||||
#cacheDurationSeconds;
|
||||
#map = new Map();
|
||||
constructor(cacheDurationSeconds) {
|
||||
this.#cacheDurationSeconds = cacheDurationSeconds;
|
||||
}
|
||||
clear() {
|
||||
this.#map.clear();
|
||||
}
|
||||
get(key) {
|
||||
const entry = this.#map.get(key);
|
||||
if (entry?.value != null) {
|
||||
if (this.#cacheDurationSeconds === 'Infinity') {
|
||||
return entry.value;
|
||||
}
|
||||
const ageSeconds = process.hrtime(entry.lastSeen)[0];
|
||||
if (ageSeconds < this.#cacheDurationSeconds) {
|
||||
// cache hit woo!
|
||||
return entry.value;
|
||||
}
|
||||
// key has expired - clean it up to free up memory
|
||||
this.#map.delete(key);
|
||||
}
|
||||
// no hit :'(
|
||||
return undefined;
|
||||
}
|
||||
set(key, value) {
|
||||
this.#map.set(key, {
|
||||
lastSeen: this.#cacheDurationSeconds === 'Infinity'
|
||||
? // no need to waste time calculating the hrtime in infinity mode as there's no expiry
|
||||
ZERO_HR_TIME
|
||||
: process.hrtime(),
|
||||
value,
|
||||
});
|
||||
return this;
|
||||
}
|
||||
}
|
||||
exports.ExpiringCache = ExpiringCache;
|
||||
@@ -0,0 +1,4 @@
|
||||
import v35 from './v35.js';
|
||||
import sha1 from './sha1.js';
|
||||
var v5 = v35('v5', 0x50, sha1);
|
||||
export default v5;
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag consistent return values
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
const { upperCaseFirst } = require("../shared/string-utils");
|
||||
const { isAnySegmentReachable } = require("./utils/code-path-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether a given node is a `constructor` method in an ES6 class
|
||||
* @param {ASTNode} node A node to check
|
||||
* @returns {boolean} `true` if the node is a `constructor` method
|
||||
*/
|
||||
function isClassConstructor(node) {
|
||||
return (
|
||||
node.type === "FunctionExpression" &&
|
||||
node.parent &&
|
||||
node.parent.type === "MethodDefinition" &&
|
||||
node.parent.kind === "constructor"
|
||||
);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Require `return` statements to either always or never specify values",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/consistent-return",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
treatUndefinedAsUnspecified: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
defaultOptions: [{ treatUndefinedAsUnspecified: false }],
|
||||
|
||||
messages: {
|
||||
missingReturn: "Expected to return a value at the end of {{name}}.",
|
||||
missingReturnValue: "{{name}} expected a return value.",
|
||||
unexpectedReturnValue: "{{name}} expected no return value.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const [{ treatUndefinedAsUnspecified }] = context.options;
|
||||
let funcInfo = null;
|
||||
|
||||
/**
|
||||
* Checks whether of not the implicit returning is consistent if the last
|
||||
* code path segment is reachable.
|
||||
* @param {ASTNode} node A program/function node to check.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkLastSegment(node) {
|
||||
let loc, name;
|
||||
|
||||
/*
|
||||
* Skip if it expected no return value or unreachable.
|
||||
* When unreachable, all paths are returned or thrown.
|
||||
*/
|
||||
if (
|
||||
!funcInfo.hasReturnValue ||
|
||||
!isAnySegmentReachable(funcInfo.currentSegments) ||
|
||||
astUtils.isES5Constructor(node) ||
|
||||
isClassConstructor(node)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Adjust a location and a message.
|
||||
if (node.type === "Program") {
|
||||
// The head of program.
|
||||
loc = { line: 1, column: 0 };
|
||||
name = "program";
|
||||
} else if (node.type === "ArrowFunctionExpression") {
|
||||
// `=>` token
|
||||
loc = context.sourceCode.getTokenBefore(
|
||||
node.body,
|
||||
astUtils.isArrowToken,
|
||||
).loc;
|
||||
} else if (
|
||||
node.parent.type === "MethodDefinition" ||
|
||||
(node.parent.type === "Property" && node.parent.method)
|
||||
) {
|
||||
// Method name.
|
||||
loc = node.parent.key.loc;
|
||||
} else {
|
||||
// Function name or `function` keyword.
|
||||
loc = (node.id || context.sourceCode.getFirstToken(node)).loc;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
name = astUtils.getFunctionNameWithKind(node);
|
||||
}
|
||||
|
||||
// Reports.
|
||||
context.report({
|
||||
node,
|
||||
loc,
|
||||
messageId: "missingReturn",
|
||||
data: { name },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
// Initializes/Disposes state of each code path.
|
||||
onCodePathStart(codePath, node) {
|
||||
funcInfo = {
|
||||
upper: funcInfo,
|
||||
codePath,
|
||||
hasReturn: false,
|
||||
hasReturnValue: false,
|
||||
messageId: "",
|
||||
node,
|
||||
currentSegments: new Set(),
|
||||
};
|
||||
},
|
||||
onCodePathEnd() {
|
||||
funcInfo = funcInfo.upper;
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
onCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
},
|
||||
|
||||
onCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
// Reports a given return statement if it's inconsistent.
|
||||
ReturnStatement(node) {
|
||||
const argument = node.argument;
|
||||
let hasReturnValue = Boolean(argument);
|
||||
|
||||
if (treatUndefinedAsUnspecified && hasReturnValue) {
|
||||
hasReturnValue =
|
||||
!astUtils.isSpecificId(argument, "undefined") &&
|
||||
argument.operator !== "void";
|
||||
}
|
||||
|
||||
if (!funcInfo.hasReturn) {
|
||||
funcInfo.hasReturn = true;
|
||||
funcInfo.hasReturnValue = hasReturnValue;
|
||||
funcInfo.messageId = hasReturnValue
|
||||
? "missingReturnValue"
|
||||
: "unexpectedReturnValue";
|
||||
funcInfo.data = {
|
||||
name:
|
||||
funcInfo.node.type === "Program"
|
||||
? "Program"
|
||||
: upperCaseFirst(
|
||||
astUtils.getFunctionNameWithKind(
|
||||
funcInfo.node,
|
||||
),
|
||||
),
|
||||
};
|
||||
} else if (funcInfo.hasReturnValue !== hasReturnValue) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: funcInfo.messageId,
|
||||
data: funcInfo.data,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Reports a given program/function if the implicit returning is not consistent.
|
||||
"Program:exit": checkLastSegment,
|
||||
"FunctionDeclaration:exit": checkLastSegment,
|
||||
"FunctionExpression:exit": checkLastSegment,
|
||||
"ArrowFunctionExpression:exit": checkLastSegment,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
"use strict";
|
||||
|
||||
/* eslint consistent-return: 0 -- no default case */
|
||||
|
||||
const messages = {
|
||||
env: `
|
||||
A config object is using the "env" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "languageOptions.globals" to define global variables for your files.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
|
||||
|
||||
If you're not using "env" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
extends: `
|
||||
A config object is using the "extends" key, which is not supported in flat config system.
|
||||
|
||||
Instead of "extends", you can include config objects that you'd like to extend from directly in the flat config array.
|
||||
|
||||
If you're using "extends" in your config file, please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#predefined-and-shareable-configs
|
||||
|
||||
If you're not using "extends" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
globals: `
|
||||
A config object is using the "globals" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "languageOptions.globals" to define global variables for your files.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
|
||||
|
||||
If you're not using "globals" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
ignorePatterns: `
|
||||
A config object is using the "ignorePatterns" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "ignores" to specify files to ignore.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#ignore-files
|
||||
|
||||
If you're not using "ignorePatterns" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
noInlineConfig: `
|
||||
A config object is using the "noInlineConfig" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "linterOptions.noInlineConfig" to specify files to ignore.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#linter-options
|
||||
`,
|
||||
|
||||
overrides: `
|
||||
A config object is using the "overrides" key, which is not supported in flat config system.
|
||||
|
||||
Flat config is an array that acts like the eslintrc "overrides" array.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#glob-based-configs
|
||||
|
||||
If you're not using "overrides" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
parser: `
|
||||
A config object is using the "parser" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "languageOptions.parser" to override the default parser.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#custom-parsers
|
||||
|
||||
If you're not using "parser" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
parserOptions: `
|
||||
A config object is using the "parserOptions" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "languageOptions.parserOptions" to specify parser options.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
|
||||
|
||||
If you're not using "parserOptions" directly (it may be coming from a plugin), please see the following:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
|
||||
`,
|
||||
|
||||
reportUnusedDisableDirectives: `
|
||||
A config object is using the "reportUnusedDisableDirectives" key, which is not supported in flat config system.
|
||||
|
||||
Flat config uses "linterOptions.reportUnusedDisableDirectives" to specify files to ignore.
|
||||
|
||||
Please see the following page for information on how to convert your config object into the correct format:
|
||||
https://eslint.org/docs/latest/use/configure/migration-guide#linter-options
|
||||
`,
|
||||
|
||||
root: `
|
||||
A config object is using the "root" key, which is not supported in flat config system.
|
||||
|
||||
Flat configs always act as if they are the root config file, so this key can be safely removed.
|
||||
`,
|
||||
};
|
||||
|
||||
module.exports = function ({ key }) {
|
||||
return messages[key].trim();
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
var _class_apply_descriptor_destructure = require("./_class_apply_descriptor_destructure.cjs");
|
||||
var _class_check_private_static_access = require("./_class_check_private_static_access.cjs");
|
||||
var _class_check_private_static_field_descriptor = require("./_class_check_private_static_field_descriptor.cjs");
|
||||
|
||||
function _class_static_private_field_destructure(receiver, classConstructor, descriptor) {
|
||||
_class_check_private_static_access._(receiver, classConstructor);
|
||||
_class_check_private_static_field_descriptor._(descriptor, "set");
|
||||
|
||||
return _class_apply_descriptor_destructure._(receiver, descriptor);
|
||||
}
|
||||
exports._ = _class_static_private_field_destructure;
|
||||
@@ -0,0 +1,15 @@
|
||||
export type Options = [
|
||||
{
|
||||
allowArgumentsExplicitlyTypedAsAny?: boolean;
|
||||
allowDirectConstAssertionInArrowFunctions?: boolean;
|
||||
allowedNames?: string[];
|
||||
allowHigherOrderFunctions?: boolean;
|
||||
allowTypedFunctionExpressions?: boolean;
|
||||
allowOverloadFunctions?: boolean;
|
||||
}
|
||||
];
|
||||
export type MessageIds = 'anyTypedArg' | 'anyTypedArgUnnamed' | 'missingArgType' | 'missingArgTypeUnnamed' | 'missingReturnType';
|
||||
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,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ClassStaticBlockScope = void 0;
|
||||
const ScopeBase_1 = require("./ScopeBase");
|
||||
const ScopeType_1 = require("./ScopeType");
|
||||
class ClassStaticBlockScope extends ScopeBase_1.ScopeBase {
|
||||
constructor(scopeManager, upperScope, block) {
|
||||
super(scopeManager, ScopeType_1.ScopeType.classStaticBlock, upperScope, block, false);
|
||||
}
|
||||
}
|
||||
exports.ClassStaticBlockScope = ClassStaticBlockScope;
|
||||
@@ -0,0 +1,20 @@
|
||||
| Suite | Browser | reg | fn if | fn if reverse | escape31 | native |
|
||||
| :----------- | :-------------------------------------- | --------------: | --------------: | --------------: | ----------------: | ----------------: |
|
||||
| escape-long | Chrome 60.0.3112 (Windows 7 0.0.0) | 85.71% (±1.21%) | 51.57% (±0.51%) | 45.53% (±0.41%) | 55.48% (±0.59%) | *100.00% (±1.04%) |
|
||||
| escape-long | Chrome Mobile 55.0.2883 (Android 6.0.0) | 75.44% (±1.88%) | 44.27% (±0.71%) | 32.00% (±0.87%) | 48.22% (±1.28%) | *100.00% (±2.41%) |
|
||||
| escape-long | Edge 14.14393.0 (Windows 10 0.0.0) | 62.92% (±1.03%) | 26.70% (±0.52%) | 14.32% (±0.31%) | 28.07% (±0.58%) | *100.00% (±2.04%) |
|
||||
| escape-long | Firefox 54.0.0 (Windows 7 0.0.0) | 63.41% (±1.86%) | 35.40% (±0.88%) | 35.65% (±0.79%) | 35.55% (±0.90%) | *100.00% (±4.52%) |
|
||||
| escape-long | IE 10.0.0 (Windows 7 0.0.0) | 62.29% (±1.26%) | 17.96% (±0.51%) | 12.78% (±0.16%) | 18.24% (±0.53%) | *100.00% (±2.60%) |
|
||||
| escape-long | IE 11.0.0 (Windows 7 0.0.0) | 50.37% (±1.20%) | 18.17% (±0.27%) | 9.52% (±0.38%) | 18.70% (±0.37%) | *100.00% (±1.35%) |
|
||||
| escape-long | IE 9.0.0 (Windows 7 0.0.0) | 49.81% (±0.36%) | 15.02% (±0.22%) | 9.86% (±0.20%) | 15.95% (±0.30%) | *100.00% (±1.20%) |
|
||||
| escape-long | Mobile Safari 10.0.0 (iOS 10.3.0) | 33.43% (±0.33%) | 7.66% (±0.07%) | 6.85% (±0.12%) | 7.72% (±0.12%) | *100.00% (±0.93%) |
|
||||
| escape-long | Safari 10.0.1 (Mac OS X 10.12.1) | 37.81% (±1.08%) | 10.44% (±0.22%) | 9.35% (±0.15%) | 11.29% (±0.15%) | *100.00% (±2.80%) |
|
||||
| escape-short | Chrome 60.0.3112 (Windows 7 0.0.0) | 36.28% (±0.64%) | 52.74% (±0.75%) | 55.04% (±0.87%) | 78.10% (±1.26%) | *100.00% (±1.62%) |
|
||||
| escape-short | Chrome Mobile 55.0.2883 (Android 6.0.0) | 29.79% (±2.20%) | 48.04% (±1.00%) | 44.01% (±1.07%) | 71.78% (±1.59%) | *100.00% (±2.92%) |
|
||||
| escape-short | Edge 14.14393.0 (Windows 10 0.0.0) | 40.85% (±0.61%) | 47.58% (±0.90%) | 39.69% (±0.69%) | 67.54% (±1.17%) | *100.00% (±1.29%) |
|
||||
| escape-short | Firefox 54.0.0 (Windows 7 0.0.0) | 40.73% (±1.06%) | 87.76% (±2.36%) | 86.55% (±2.36%) | *100.00% (±2.52%) | 75.19% (±4.48%) |
|
||||
| escape-short | IE 10.0.0 (Windows 7 0.0.0) | 44.12% (±1.09%) | 42.19% (±1.18%) | 38.04% (±0.62%) | 45.28% (±1.21%) | *100.00% (±2.44%) |
|
||||
| escape-short | IE 11.0.0 (Windows 7 0.0.0) | 41.97% (±0.71%) | 46.65% (±0.90%) | 30.08% (±0.62%) | 58.80% (±1.20%) | *100.00% (±1.81%) |
|
||||
| escape-short | IE 9.0.0 (Windows 7 0.0.0) | 36.31% (±0.52%) | 36.81% (±0.52%) | 24.71% (±0.31%) | 41.89% (±0.60%) | *100.00% (±1.31%) |
|
||||
| escape-short | Mobile Safari 10.0.0 (iOS 10.3.0) | 26.35% (±0.86%) | 27.14% (±0.35%) | 28.60% (±0.29%) | 27.98% (±0.71%) | *100.00% (±2.54%) |
|
||||
| escape-short | Safari 10.0.1 (Mac OS X 10.12.1) | 28.25% (±0.82%) | 28.26% (±0.61%) | 31.96% (±0.42%) | 37.83% (±0.44%) | *100.00% (±2.77%) |
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Blockhash as Base58 string.
|
||||
*/
|
||||
export type Blockhash = string;
|
||||
@@ -0,0 +1,443 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABILITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference lib="es2015.symbol" />
|
||||
/// <reference lib="es2015.iterable" />
|
||||
|
||||
/**
|
||||
* A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
|
||||
* of bytes could not be allocated an exception is raised.
|
||||
*/
|
||||
interface Float16Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
|
||||
/**
|
||||
* The size in bytes of each element in the array.
|
||||
*/
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* The ArrayBuffer instance referenced by the array.
|
||||
*/
|
||||
readonly buffer: TArrayBuffer;
|
||||
|
||||
/**
|
||||
* The length in bytes of the array.
|
||||
*/
|
||||
readonly byteLength: number;
|
||||
|
||||
/**
|
||||
* The offset in bytes of the array.
|
||||
*/
|
||||
readonly byteOffset: number;
|
||||
|
||||
/**
|
||||
* Returns the item located at the specified index.
|
||||
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
|
||||
*/
|
||||
at(index: number): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param predicate A function that accepts up to three arguments. The every method calls
|
||||
* the predicate function for each element in the array until the predicate returns a value
|
||||
* which is coercible to the Boolean value false, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
fill(value: number, start?: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param predicate A function that accepts up to three arguments. The filter method calls
|
||||
* the predicate function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: this,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: this,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: this,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
includes(searchElement: number, fromIndex?: number): boolean;
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
indexOf(searchElement: number, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
join(separator?: string): string;
|
||||
|
||||
/**
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
lastIndexOf(searchElement: number, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* The length of the array.
|
||||
*/
|
||||
readonly length: number;
|
||||
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
|
||||
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
|
||||
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Reverses the elements in an Array.
|
||||
*/
|
||||
reverse(): this;
|
||||
|
||||
/**
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
set(array: ArrayLike<number>, offset?: number): void;
|
||||
|
||||
/**
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
|
||||
*/
|
||||
slice(start?: number, end?: number): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param predicate A function that accepts up to three arguments. The some method calls
|
||||
* the predicate function for each element in the array until the predicate returns a value
|
||||
* which is coercible to the Boolean value true, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
*/
|
||||
sort(compareFn?: (a: number, b: number) => number): this;
|
||||
|
||||
/**
|
||||
* Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin?: number, end?: number): Float16Array<TArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Converts a number to a string by using the current locale.
|
||||
*/
|
||||
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Returns a string representation of an array.
|
||||
*/
|
||||
toString(): string;
|
||||
|
||||
/** Returns the primitive value of the specified object. */
|
||||
valueOf(): this;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Float16Array<ArrayBuffer>;
|
||||
|
||||
[index: number]: number;
|
||||
|
||||
[Symbol.iterator](): ArrayIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns an array of key, value pairs for every entry in the array
|
||||
*/
|
||||
entries(): ArrayIterator<[number, number]>;
|
||||
|
||||
/**
|
||||
* Returns an list of keys in the array
|
||||
*/
|
||||
keys(): ArrayIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns an list of values in the array
|
||||
*/
|
||||
values(): ArrayIterator<number>;
|
||||
|
||||
readonly [Symbol.toStringTag]: "Float16Array";
|
||||
}
|
||||
|
||||
interface Float16ArrayConstructor {
|
||||
readonly prototype: Float16Array<ArrayBufferLike>;
|
||||
new (length?: number): Float16Array<ArrayBuffer>;
|
||||
new (array: ArrayLike<number> | Iterable<number>): Float16Array<ArrayBuffer>;
|
||||
new <TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(buffer: TArrayBuffer, byteOffset?: number, length?: number): Float16Array<TArrayBuffer>;
|
||||
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float16Array<ArrayBuffer>;
|
||||
new (array: ArrayLike<number> | ArrayBuffer): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* The size in bytes of each element in the array.
|
||||
*/
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
of(...items: number[]): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param elements An iterable object to convert to an array.
|
||||
*/
|
||||
from(elements: Iterable<number>): Float16Array<ArrayBuffer>;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param elements An iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
}
|
||||
declare var Float16Array: Float16ArrayConstructor;
|
||||
|
||||
interface Math {
|
||||
/**
|
||||
* Returns the nearest half precision float representation of a number.
|
||||
* @param x A numeric expression.
|
||||
*/
|
||||
f16round(x: number): number;
|
||||
}
|
||||
|
||||
interface DataView<TArrayBuffer extends ArrayBufferLike> {
|
||||
/**
|
||||
* Gets the Float16 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be read.
|
||||
*/
|
||||
getFloat16(byteOffset: number, littleEndian?: boolean): number;
|
||||
|
||||
/**
|
||||
* Stores an Float16 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written.
|
||||
*/
|
||||
setFloat16(byteOffset: number, value: number, littleEndian?: boolean): void;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
// do not edit .js files directly - edit src/index.jst
|
||||
|
||||
|
||||
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
|
||||
|
||||
|
||||
module.exports = function equal(a, b) {
|
||||
if (a === b) return true;
|
||||
|
||||
if (a && b && typeof a == 'object' && typeof b == 'object') {
|
||||
if (a.constructor !== b.constructor) return false;
|
||||
|
||||
var length, i, keys;
|
||||
if (Array.isArray(a)) {
|
||||
length = a.length;
|
||||
if (length != b.length) return false;
|
||||
for (i = length; i-- !== 0;)
|
||||
if (!equal(a[i], b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if ((a instanceof Map) && (b instanceof Map)) {
|
||||
if (a.size !== b.size) return false;
|
||||
for (i of a.entries())
|
||||
if (!b.has(i[0])) return false;
|
||||
for (i of a.entries())
|
||||
if (!equal(i[1], b.get(i[0]))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((a instanceof Set) && (b instanceof Set)) {
|
||||
if (a.size !== b.size) return false;
|
||||
for (i of a.entries())
|
||||
if (!b.has(i[0])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
|
||||
length = a.length;
|
||||
if (length != b.length) return false;
|
||||
for (i = length; i-- !== 0;)
|
||||
if (a[i] !== b[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
|
||||
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
|
||||
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
|
||||
|
||||
keys = Object.keys(a);
|
||||
length = keys.length;
|
||||
if (length !== Object.keys(b).length) return false;
|
||||
|
||||
for (i = length; i-- !== 0;)
|
||||
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
|
||||
|
||||
for (i = length; i-- !== 0;) {
|
||||
var key = keys[i];
|
||||
|
||||
if (!equal(a[key], b[key])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// true if both NaN, false otherwise
|
||||
return a!==a && b!==b;
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
declare const pathExists: {
|
||||
/**
|
||||
Check if a path exists.
|
||||
|
||||
@returns Whether the path exists.
|
||||
|
||||
@example
|
||||
```
|
||||
// foo.ts
|
||||
import pathExists = require('path-exists');
|
||||
|
||||
(async () => {
|
||||
console.log(await pathExists('foo.ts'));
|
||||
//=> true
|
||||
})();
|
||||
```
|
||||
*/
|
||||
(path: string): Promise<boolean>;
|
||||
|
||||
/**
|
||||
Synchronously check if a path exists.
|
||||
|
||||
@returns Whether the path exists.
|
||||
*/
|
||||
sync(path: string): boolean;
|
||||
};
|
||||
|
||||
export = pathExists;
|
||||
@@ -0,0 +1,356 @@
|
||||
import assert from 'assert'
|
||||
import { serialize } from './serializer'
|
||||
import BufferList from './testing/buffer-list'
|
||||
|
||||
describe('serializer', () => {
|
||||
it('builds startup message', function () {
|
||||
const actual = serialize.startup({
|
||||
user: 'brian',
|
||||
database: 'bang',
|
||||
})
|
||||
assert.deepEqual(
|
||||
actual,
|
||||
new BufferList()
|
||||
.addInt16(3)
|
||||
.addInt16(0)
|
||||
.addCString('user')
|
||||
.addCString('brian')
|
||||
.addCString('database')
|
||||
.addCString('bang')
|
||||
.addCString('client_encoding')
|
||||
.addCString('UTF8')
|
||||
.addCString('')
|
||||
.join(true)
|
||||
)
|
||||
})
|
||||
|
||||
it('builds password message', function () {
|
||||
const actual = serialize.password('!')
|
||||
assert.deepEqual(actual, new BufferList().addCString('!').join(true, 'p'))
|
||||
})
|
||||
|
||||
it('builds request ssl message', function () {
|
||||
const actual = serialize.requestSsl()
|
||||
const expected = new BufferList().addInt32(80877103).join(true)
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds SASLInitialResponseMessage message', function () {
|
||||
const actual = serialize.sendSASLInitialResponseMessage('mech', 'data')
|
||||
assert.deepEqual(actual, new BufferList().addCString('mech').addInt32(4).addString('data').join(true, 'p'))
|
||||
})
|
||||
|
||||
it('builds SCRAMClientFinalMessage message', function () {
|
||||
const actual = serialize.sendSCRAMClientFinalMessage('data')
|
||||
assert.deepEqual(actual, new BufferList().addString('data').join(true, 'p'))
|
||||
})
|
||||
|
||||
it('builds query message', function () {
|
||||
const txt = 'select * from boom'
|
||||
const actual = serialize.query(txt)
|
||||
assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q'))
|
||||
})
|
||||
|
||||
describe('parse message', () => {
|
||||
it('builds parse message', function () {
|
||||
const actual = serialize.parse({ text: '!' })
|
||||
const expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds parse message with named query', function () {
|
||||
const actual = serialize.parse({
|
||||
name: 'boom',
|
||||
text: 'select * from boom',
|
||||
types: [],
|
||||
})
|
||||
const expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('with multiple parameters', function () {
|
||||
const actual = serialize.parse({
|
||||
name: 'force',
|
||||
text: 'select * from bang where name = $1',
|
||||
types: [1, 2, 3, 4],
|
||||
})
|
||||
const expected = new BufferList()
|
||||
.addCString('force')
|
||||
.addCString('select * from bang where name = $1')
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.addInt32(2)
|
||||
.addInt32(3)
|
||||
.addInt32(4)
|
||||
.join(true, 'P')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bind messages', function () {
|
||||
it('with no values', function () {
|
||||
const actual = serialize.bind()
|
||||
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('')
|
||||
.addCString('')
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
it('with named statement, portal, and values', function () {
|
||||
const actual = serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
})
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
it('encodes a multi-byte string param with its UTF-8 byte length, not char length', function () {
|
||||
// Guards the single-pass addInt32PrefixedString write path: the Int32
|
||||
// length prefix must be the UTF-8 byte count, not String.length. 'héllo中🎉'
|
||||
// is 7 code points / 8 UTF-16 code units but 13 UTF-8 bytes.
|
||||
const value = 'héllo中🎉'
|
||||
const bytes = Buffer.from(value, 'utf8')
|
||||
assert.notEqual(bytes.length, value.length) // sanity: the divergence we're testing
|
||||
const actual = serialize.bind({ values: [value] })
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('') // portal
|
||||
.addCString('') // statement
|
||||
.addInt16(1) // param format code count
|
||||
.addInt16(0) // format code for the one value (text)
|
||||
.addInt16(1) // value count
|
||||
.addInt32(bytes.length) // 13 — the UTF-8 byte length, NOT value.length (8)
|
||||
.add(bytes)
|
||||
.addInt16(1) // result format code count
|
||||
.addInt16(0) // result format (text)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
})
|
||||
|
||||
it('with custom valueMapper', function () {
|
||||
const actual = serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
valueMapper: () => null,
|
||||
})
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
it('with named statement, portal, and buffer value', function () {
|
||||
const actual = serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, Buffer.from('zing', 'utf8')],
|
||||
})
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4) // value count
|
||||
.addInt16(0) // string
|
||||
.addInt16(0) // string
|
||||
.addInt16(0) // string
|
||||
.addInt16(1) // binary
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing', 'utf-8'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
describe('builds execute message', function () {
|
||||
it('for unamed portal with no row limit', function () {
|
||||
const actual = serialize.execute()
|
||||
const expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
it('for named portal with row limit', function () {
|
||||
const actual = serialize.execute({
|
||||
portal: 'my favorite portal',
|
||||
rows: 100,
|
||||
})
|
||||
const expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
})
|
||||
|
||||
it('builds flush command', function () {
|
||||
const actual = serialize.flush()
|
||||
const expected = new BufferList().join(true, 'H')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds sync command', function () {
|
||||
const actual = serialize.sync()
|
||||
const expected = new BufferList().join(true, 'S')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds end command', function () {
|
||||
const actual = serialize.end()
|
||||
const expected = Buffer.from([0x58, 0, 0, 0, 4])
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
describe('builds describe command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serialize.describe({ type: 'S', name: 'bang' })
|
||||
const expected = new BufferList().addChar('S').addCString('bang').join(true, 'D')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serialize.describe({ type: 'P' })
|
||||
const expected = new BufferList().addChar('P').addCString('').join(true, 'D')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('builds close command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serialize.close({ type: 'S', name: 'bang' })
|
||||
const expected = new BufferList().addChar('S').addCString('bang').join(true, 'C')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serialize.close({ type: 'P' })
|
||||
const expected = new BufferList().addChar('P').addCString('').join(true, 'C')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('copy messages', function () {
|
||||
it('builds copyFromChunk', () => {
|
||||
const actual = serialize.copyData(Buffer.from([1, 2, 3]))
|
||||
const expected = new BufferList().add(Buffer.from([1, 2, 3])).join(true, 'd')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds copy fail', () => {
|
||||
const actual = serialize.copyFail('err!')
|
||||
const expected = new BufferList().addCString('err!').join(true, 'f')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds copy done', () => {
|
||||
const actual = serialize.copyDone()
|
||||
const expected = new BufferList().join(true, 'c')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
|
||||
it('builds cancel message', () => {
|
||||
const actual = serialize.cancel(3, 4)
|
||||
const expected = new BufferList().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true)
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
describe('bind error recovery', () => {
|
||||
const throwingMapper = () => {
|
||||
throw new Error('valueMapper error')
|
||||
}
|
||||
|
||||
it('produces correct bind output after a valueMapper exception', () => {
|
||||
assert.throws(() => {
|
||||
serialize.bind({
|
||||
values: ['fail'],
|
||||
valueMapper: throwingMapper,
|
||||
})
|
||||
}, /valueMapper error/)
|
||||
|
||||
const actual = serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
})
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang')
|
||||
.addCString('woo')
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
it('produces correct output from other serializer methods after a failed bind', () => {
|
||||
assert.throws(() => {
|
||||
serialize.bind({
|
||||
values: ['fail'],
|
||||
valueMapper: throwingMapper,
|
||||
})
|
||||
}, /valueMapper error/)
|
||||
|
||||
const parseActual = serialize.parse({ text: '!' })
|
||||
const parseExpected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P')
|
||||
assert.deepEqual(parseActual, parseExpected)
|
||||
|
||||
const queryActual = serialize.query('select 1')
|
||||
const queryExpected = new BufferList().addCString('select 1').join(true, 'Q')
|
||||
assert.deepEqual(queryActual, queryExpected)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
function _writeOnlyError(r) {
|
||||
throw new TypeError('"' + r + '" is write-only');
|
||||
}
|
||||
module.exports = _writeOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1,138 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const util = __importStar(require("../core/util.cjs"));
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "문자", verb: "to have" },
|
||||
file: { unit: "바이트", verb: "to have" },
|
||||
array: { unit: "개", verb: "to have" },
|
||||
set: { unit: "개", verb: "to have" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "입력",
|
||||
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",
|
||||
};
|
||||
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 suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const unit = sizing?.unit ?? "요소";
|
||||
if (sizing)
|
||||
return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`;
|
||||
return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? "이상" : "초과";
|
||||
const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const unit = sizing?.unit ?? "요소";
|
||||
if (sizing) {
|
||||
return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`;
|
||||
}
|
||||
return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`;
|
||||
}
|
||||
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 `인식할 수 없는 키: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `잘못된 키: ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return `잘못된 입력`;
|
||||
case "invalid_element":
|
||||
return `잘못된 값: ${issue.origin}`;
|
||||
default:
|
||||
return `잘못된 입력`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
@@ -0,0 +1,74 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-Zhafd14U.mjs";
|
||||
//#region ../../node_modules/.pnpm/oxc-parser@0.144.0/node_modules/oxc-parser/src-js/wrap.js
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
function wrap(result) {
|
||||
let program, module, comments, errors;
|
||||
return {
|
||||
get program() {
|
||||
if (!program) program = jsonParseAst(result.program);
|
||||
return program;
|
||||
},
|
||||
get module() {
|
||||
if (!module) module = result.module;
|
||||
return module;
|
||||
},
|
||||
get comments() {
|
||||
if (!comments) comments = result.comments;
|
||||
return comments;
|
||||
},
|
||||
get errors() {
|
||||
if (!errors) errors = result.errors;
|
||||
return errors;
|
||||
}
|
||||
};
|
||||
}
|
||||
function jsonParseAst(programJson) {
|
||||
const { node: program, fixes } = JSON.parse(programJson);
|
||||
for (const fixPath of fixes) applyFix(program, fixPath);
|
||||
return program;
|
||||
}
|
||||
function applyFix(program, fixPath) {
|
||||
let node = program;
|
||||
for (const key of fixPath) node = node[key];
|
||||
if (node.bigint) node.value = BigInt(node.bigint);
|
||||
else try {
|
||||
node.value = RegExp(node.regex.pattern, node.regex.flags);
|
||||
} catch {}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/utils/parse.ts
|
||||
/**
|
||||
* Parse JS/TS source asynchronously on a separate thread.
|
||||
*
|
||||
* Note that not all of the workload can happen on a separate thread.
|
||||
* Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects
|
||||
* has to happen on current thread. This synchronous deserialization work typically outweighs
|
||||
* the asynchronous parsing by a factor of between 3 and 20.
|
||||
*
|
||||
* i.e. the majority of the workload cannot be parallelized by using this method.
|
||||
*
|
||||
* Generally {@linkcode parseSync} is preferable to use as it does not have the overhead of spawning a thread.
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads.
|
||||
*
|
||||
* @category Utilities
|
||||
*/
|
||||
async function parse(filename, sourceText, options) {
|
||||
return wrap(await (0, import_binding.parse)(filename, sourceText, options));
|
||||
}
|
||||
/**
|
||||
* Parse JS/TS source synchronously on current thread.
|
||||
*
|
||||
* This is generally preferable over {@linkcode parse} (async) as it does not have the overhead
|
||||
* of spawning a thread, and the majority of the workload cannot be parallelized anyway
|
||||
* (see {@linkcode parse} documentation for details).
|
||||
*
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads
|
||||
* with {@linkcode parseSync} rather than using {@linkcode parse}.
|
||||
*
|
||||
* @category Utilities
|
||||
*/
|
||||
function parseSync(filename, sourceText, options) {
|
||||
return wrap((0, import_binding.parseSync)(filename, sourceText, options));
|
||||
}
|
||||
//#endregion
|
||||
export { parseSync as n, parse as t };
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
|
||||
module.exports = {
|
||||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
|
||||
definitions: {
|
||||
simpleTypes: metaSchema.definitions.simpleTypes
|
||||
},
|
||||
type: 'object',
|
||||
dependencies: {
|
||||
schema: ['validate'],
|
||||
$data: ['validate'],
|
||||
statements: ['inline'],
|
||||
valid: {not: {required: ['macro']}}
|
||||
},
|
||||
properties: {
|
||||
type: metaSchema.properties.type,
|
||||
schema: {type: 'boolean'},
|
||||
statements: {type: 'boolean'},
|
||||
dependencies: {
|
||||
type: 'array',
|
||||
items: {type: 'string'}
|
||||
},
|
||||
metaSchema: {type: 'object'},
|
||||
modifying: {type: 'boolean'},
|
||||
valid: {type: 'boolean'},
|
||||
$data: {type: 'boolean'},
|
||||
async: {type: 'boolean'},
|
||||
errors: {
|
||||
anyOf: [
|
||||
{type: 'boolean'},
|
||||
{const: 'full'}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,289 @@
|
||||
import { SolanaError, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE } from '@solana/errors';
|
||||
import { combineCodec, createDecoder, createEncoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';
|
||||
|
||||
// src/assertions.ts
|
||||
function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
|
||||
if (value < min || value > max) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {
|
||||
codecDescription,
|
||||
max,
|
||||
min,
|
||||
value
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// src/common.ts
|
||||
var Endian = /* @__PURE__ */ ((Endian2) => {
|
||||
Endian2[Endian2["Little"] = 0] = "Little";
|
||||
Endian2[Endian2["Big"] = 1] = "Big";
|
||||
return Endian2;
|
||||
})(Endian || {});
|
||||
function isLittleEndian(config) {
|
||||
return config?.endian === 1 /* Big */ ? false : true;
|
||||
}
|
||||
function numberEncoderFactory(input) {
|
||||
return createEncoder({
|
||||
fixedSize: input.size,
|
||||
write(value, bytes, offset) {
|
||||
if (input.range) {
|
||||
assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
|
||||
}
|
||||
const arrayBuffer = new ArrayBuffer(input.size);
|
||||
input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
|
||||
bytes.set(new Uint8Array(arrayBuffer), offset);
|
||||
return offset + input.size;
|
||||
}
|
||||
});
|
||||
}
|
||||
function numberDecoderFactory(input) {
|
||||
return createDecoder({
|
||||
fixedSize: input.size,
|
||||
read(bytes, offset = 0) {
|
||||
assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
|
||||
assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
|
||||
const view = new DataView(toArrayBuffer(bytes, offset, input.size));
|
||||
return [input.get(view, isLittleEndian(input.config)), offset + input.size];
|
||||
}
|
||||
});
|
||||
}
|
||||
function toArrayBuffer(bytes, offset, length) {
|
||||
const bytesOffset = bytes.byteOffset + (offset ?? 0);
|
||||
const bytesLength = length ?? bytes.byteLength;
|
||||
return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
|
||||
}
|
||||
|
||||
// src/f32.ts
|
||||
var getF32Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "f32",
|
||||
set: (view, value, le) => view.setFloat32(0, Number(value), le),
|
||||
size: 4
|
||||
});
|
||||
var getF32Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getFloat32(0, le),
|
||||
name: "f32",
|
||||
size: 4
|
||||
});
|
||||
var getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));
|
||||
var getF64Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "f64",
|
||||
set: (view, value, le) => view.setFloat64(0, Number(value), le),
|
||||
size: 8
|
||||
});
|
||||
var getF64Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getFloat64(0, le),
|
||||
name: "f64",
|
||||
size: 8
|
||||
});
|
||||
var getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));
|
||||
var getI128Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "i128",
|
||||
range: [-BigInt("0x7fffffffffffffffffffffffffffffff") - 1n, BigInt("0x7fffffffffffffffffffffffffffffff")],
|
||||
set: (view, value, le) => {
|
||||
const leftOffset = le ? 8 : 0;
|
||||
const rightOffset = le ? 0 : 8;
|
||||
const rightMask = 0xffffffffffffffffn;
|
||||
view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);
|
||||
view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
|
||||
},
|
||||
size: 16
|
||||
});
|
||||
var getI128Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => {
|
||||
const leftOffset = le ? 8 : 0;
|
||||
const rightOffset = le ? 0 : 8;
|
||||
const left = view.getBigInt64(leftOffset, le);
|
||||
const right = view.getBigUint64(rightOffset, le);
|
||||
return (left << 64n) + right;
|
||||
},
|
||||
name: "i128",
|
||||
size: 16
|
||||
});
|
||||
var getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));
|
||||
var getI16Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "i16",
|
||||
range: [-Number("0x7fff") - 1, Number("0x7fff")],
|
||||
set: (view, value, le) => view.setInt16(0, Number(value), le),
|
||||
size: 2
|
||||
});
|
||||
var getI16Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getInt16(0, le),
|
||||
name: "i16",
|
||||
size: 2
|
||||
});
|
||||
var getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));
|
||||
var getI32Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "i32",
|
||||
range: [-Number("0x7fffffff") - 1, Number("0x7fffffff")],
|
||||
set: (view, value, le) => view.setInt32(0, Number(value), le),
|
||||
size: 4
|
||||
});
|
||||
var getI32Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getInt32(0, le),
|
||||
name: "i32",
|
||||
size: 4
|
||||
});
|
||||
var getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));
|
||||
var getI64Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "i64",
|
||||
range: [-BigInt("0x7fffffffffffffff") - 1n, BigInt("0x7fffffffffffffff")],
|
||||
set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),
|
||||
size: 8
|
||||
});
|
||||
var getI64Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getBigInt64(0, le),
|
||||
name: "i64",
|
||||
size: 8
|
||||
});
|
||||
var getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));
|
||||
var getI8Encoder = () => numberEncoderFactory({
|
||||
name: "i8",
|
||||
range: [-Number("0x7f") - 1, Number("0x7f")],
|
||||
set: (view, value) => view.setInt8(0, Number(value)),
|
||||
size: 1
|
||||
});
|
||||
var getI8Decoder = () => numberDecoderFactory({
|
||||
get: (view) => view.getInt8(0),
|
||||
name: "i8",
|
||||
size: 1
|
||||
});
|
||||
var getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());
|
||||
var getShortU16Encoder = () => createEncoder({
|
||||
getSizeFromValue: (value) => {
|
||||
if (value <= 127) return 1;
|
||||
if (value <= 16383) return 2;
|
||||
return 3;
|
||||
},
|
||||
maxSize: 3,
|
||||
write: (value, bytes, offset) => {
|
||||
assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
|
||||
const shortU16Bytes = [0];
|
||||
for (let ii = 0; ; ii += 1) {
|
||||
const alignedValue = Number(value) >> ii * 7;
|
||||
if (alignedValue === 0) {
|
||||
break;
|
||||
}
|
||||
const nextSevenBits = 127 & alignedValue;
|
||||
shortU16Bytes[ii] = nextSevenBits;
|
||||
if (ii > 0) {
|
||||
shortU16Bytes[ii - 1] |= 128;
|
||||
}
|
||||
}
|
||||
bytes.set(shortU16Bytes, offset);
|
||||
return offset + shortU16Bytes.length;
|
||||
}
|
||||
});
|
||||
var getShortU16Decoder = () => createDecoder({
|
||||
maxSize: 3,
|
||||
read: (bytes, offset) => {
|
||||
let value = 0;
|
||||
let byteCount = 0;
|
||||
while (++byteCount) {
|
||||
const byteIndex = byteCount - 1;
|
||||
const currentByte = bytes[offset + byteIndex];
|
||||
const nextSevenBits = 127 & currentByte;
|
||||
value |= nextSevenBits << byteIndex * 7;
|
||||
if ((currentByte & 128) === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return [value, offset + byteCount];
|
||||
}
|
||||
});
|
||||
var getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());
|
||||
var getU128Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "u128",
|
||||
range: [0n, BigInt("0xffffffffffffffffffffffffffffffff")],
|
||||
set: (view, value, le) => {
|
||||
const leftOffset = le ? 8 : 0;
|
||||
const rightOffset = le ? 0 : 8;
|
||||
const rightMask = 0xffffffffffffffffn;
|
||||
view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);
|
||||
view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
|
||||
},
|
||||
size: 16
|
||||
});
|
||||
var getU128Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => {
|
||||
const leftOffset = le ? 8 : 0;
|
||||
const rightOffset = le ? 0 : 8;
|
||||
const left = view.getBigUint64(leftOffset, le);
|
||||
const right = view.getBigUint64(rightOffset, le);
|
||||
return (left << 64n) + right;
|
||||
},
|
||||
name: "u128",
|
||||
size: 16
|
||||
});
|
||||
var getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));
|
||||
var getU16Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "u16",
|
||||
range: [0, Number("0xffff")],
|
||||
set: (view, value, le) => view.setUint16(0, Number(value), le),
|
||||
size: 2
|
||||
});
|
||||
var getU16Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getUint16(0, le),
|
||||
name: "u16",
|
||||
size: 2
|
||||
});
|
||||
var getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));
|
||||
var getU32Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "u32",
|
||||
range: [0, Number("0xffffffff")],
|
||||
set: (view, value, le) => view.setUint32(0, Number(value), le),
|
||||
size: 4
|
||||
});
|
||||
var getU32Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getUint32(0, le),
|
||||
name: "u32",
|
||||
size: 4
|
||||
});
|
||||
var getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));
|
||||
var getU64Encoder = (config = {}) => numberEncoderFactory({
|
||||
config,
|
||||
name: "u64",
|
||||
range: [0n, BigInt("0xffffffffffffffff")],
|
||||
set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),
|
||||
size: 8
|
||||
});
|
||||
var getU64Decoder = (config = {}) => numberDecoderFactory({
|
||||
config,
|
||||
get: (view, le) => view.getBigUint64(0, le),
|
||||
name: "u64",
|
||||
size: 8
|
||||
});
|
||||
var getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));
|
||||
var getU8Encoder = () => numberEncoderFactory({
|
||||
name: "u8",
|
||||
range: [0, Number("0xff")],
|
||||
set: (view, value) => view.setUint8(0, Number(value)),
|
||||
size: 1
|
||||
});
|
||||
var getU8Decoder = () => numberDecoderFactory({
|
||||
get: (view) => view.getUint8(0),
|
||||
name: "u8",
|
||||
size: 1
|
||||
});
|
||||
var getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());
|
||||
|
||||
export { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };
|
||||
//# sourceMappingURL=index.node.mjs.map
|
||||
//# sourceMappingURL=index.node.mjs.map
|
||||
@@ -0,0 +1,946 @@
|
||||
import { DeepBrandOptions, DeepBrandOptionsDefaults, StrictEqualUsingBranding, DeepBrandPropNotes, DeepBrandPropNotesOptions, DeepBrandPropNotesOptionsDefaults } from './branding';
|
||||
import type { ExpectAny, ExpectArray, ExpectBigInt, ExpectBoolean, ExpectFunction, ExpectNever, ExpectNull, ExpectNullable, ExpectNumber, ExpectObject, ExpectString, ExpectSymbol, ExpectUndefined, ExpectUnknown, ExpectVoid, MismatchInfo, Scolder } from './messages';
|
||||
import type { ConstructorOverloadParameters, OverloadParameters, OverloadReturnTypes, OverloadThisParameterTypes, OverloadsNarrowedByParameters } from './overloads';
|
||||
import type { AValue, DeepPickMatchingProps, Extends, IsUnion, MismatchArgs, Not, StrictEqualUsingTSInternalIdenticalToOperator } from './utils';
|
||||
export * from './branding';
|
||||
export * from './messages';
|
||||
export * from './overloads';
|
||||
export * from './utils';
|
||||
/**
|
||||
* Represents the positive assertion methods available for type checking in the
|
||||
* {@linkcode expectTypeOf()} utility.
|
||||
*/
|
||||
export interface PositiveExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {
|
||||
positive: true;
|
||||
branded: false;
|
||||
}> {
|
||||
/**
|
||||
* Similar to jest's `expect(...).toMatchObject(...)` but for types.
|
||||
* Deeply "picks" the properties of the actual type based on the expected type, then performs a strict check to make sure the types match `Expected`.
|
||||
*
|
||||
* **Note**: optional properties on the {@linkcode Expected | expected type} are not allowed to be missing on the {@linkcode Actual | actual type}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchObjectType<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toMatchObjectType<{ a: number; c?: number }>()
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toMatchObjectType: <Expected extends IsUnion<Expected> extends true ? 'toMatchObject does not support union types' : Not<Extends<Expected, Record<string, unknown>>> extends true ? 'toMatchObject only supports object types' : StrictEqualUsingTSInternalIdenticalToOperator<DeepPickMatchingProps<Actual, Expected>, Expected> extends true ? unknown : MismatchInfo<DeepPickMatchingProps<Actual, Expected>, Expected>>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<DeepPickMatchingProps<Actual, Expected>, Expected>, true>) => true;
|
||||
/**
|
||||
* Check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()} that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toExtend<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).not.toExtend<{ b: number }>()
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toExtend: <Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>) => true;
|
||||
toEqualTypeOf: {
|
||||
/**
|
||||
* Uses TypeScript's internal technique to check for type "identicalness".
|
||||
*
|
||||
* It will check if the types are fully equal to each other.
|
||||
* It will not fail if two objects have different values, but the same type.
|
||||
* It will fail however if an object is missing a property.
|
||||
*
|
||||
* **_Unexpected failure_**? For a more permissive but less performant
|
||||
* check that accommodates for equivalent intersection types,
|
||||
* use {@linkcode branded | .branded.toEqualTypeOf()}.
|
||||
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param value - The value to compare against the expected type.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
|
||||
...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>): true;
|
||||
/**
|
||||
* Uses TypeScript's internal technique to check for type "identicalness".
|
||||
*
|
||||
* It will check if the types are fully equal to each other.
|
||||
* It will not fail if two objects have different values, but the same type.
|
||||
* It will fail however if an object is missing a property.
|
||||
*
|
||||
* **_Unexpected failure_**? For a more permissive but less performant
|
||||
* check that accommodates for equivalent intersection types,
|
||||
* use {@linkcode branded | .branded.toEqualTypeOf()}.
|
||||
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>): true;
|
||||
};
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*/
|
||||
toMatchTypeOf: {
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()}
|
||||
* that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint
|
||||
* in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param value - The value to compare against the expected type.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
|
||||
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>): true;
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()}
|
||||
* that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint
|
||||
* in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>): true;
|
||||
};
|
||||
/**
|
||||
* Checks whether an object has a given property.
|
||||
*
|
||||
* @example
|
||||
* <caption>check that properties exist</caption>
|
||||
* ```ts
|
||||
* const obj = { a: 1, b: '' }
|
||||
*
|
||||
* expectTypeOf(obj).toHaveProperty('a')
|
||||
*
|
||||
* expectTypeOf(obj).not.toHaveProperty('c')
|
||||
* ```
|
||||
*
|
||||
* @param key - The property key to check for.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toHaveProperty: <KeyType extends keyof Actual>(key: KeyType, ...MISMATCH: MismatchArgs<Extends<KeyType, keyof Actual>, true>) => KeyType extends keyof Actual ? PositiveExpectTypeOf<Actual[KeyType]> : true;
|
||||
/**
|
||||
* Inverts the result of the following assertions.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).not.toMatchTypeOf({ b: 1 })
|
||||
* ```
|
||||
*/
|
||||
not: NegativeExpectTypeOf<Actual>;
|
||||
/**
|
||||
* Intersection types can cause issues with
|
||||
* {@linkcode toEqualTypeOf | .toEqualTypeOf()}:
|
||||
* ```ts
|
||||
* // ❌ The following line doesn't compile, even though the types are arguably the same.
|
||||
* expectTypeOf<{ a: 1 } & { b: 2 }>().toEqualTypeOf<{ a: 1; b: 2 }>()
|
||||
* ```
|
||||
* This helper works around this problem by using
|
||||
* a more permissive but less performant check.
|
||||
*
|
||||
* __Note__: This comes at a performance cost, and can cause the compiler
|
||||
* to 'give up' if used with excessively deep types, so use sparingly.
|
||||
*
|
||||
* @see {@link https://github.com/mmkal/expect-type/pull/21 | Reference}
|
||||
*/
|
||||
branded: Branded<Actual, DeepBrandOptionsDefaults>;
|
||||
}
|
||||
export interface Branded<Actual, Options extends DeepBrandOptions> {
|
||||
/**
|
||||
* Uses TypeScript's internal technique to check for type "identicalness".
|
||||
*
|
||||
* It will check if the types are fully equal to each other.
|
||||
* It will not fail if two objects have different values, but the same type.
|
||||
* It will fail however if an object is missing a property.
|
||||
*
|
||||
* **_Unexpected failure_**? For a more permissive but less performant
|
||||
* check that accommodates for equivalent intersection types,
|
||||
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
|
||||
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toEqualTypeOf: <Expected extends StrictEqualUsingBranding<Actual, Expected, Options> extends true ? unknown : MismatchInfo<Actual, Expected, Options>>(...MISMATCH: MismatchArgs<StrictEqualUsingBranding<Actual, Expected, Options>, true>) => true;
|
||||
/**
|
||||
* Walk a type to find every deeply-nested path that resolves to `any` or `never`, useful for catching
|
||||
* badly-defined types hiding inside large or complex objects.
|
||||
*
|
||||
* Pass `{foundProps: {}}` to assert there are none - a type error will list the offending paths if there are.
|
||||
* Otherwise pass `foundProps` as a record of `path -> flagged type` to acknowledge the ones you expect.
|
||||
* The compiler tells you the exact paths (and what they resolve to) if you get it wrong.
|
||||
*
|
||||
* Use the `findType` type argument to search for `'any'`, `'never'`, or `'unknown'` instead of the default (`'any' | 'never'`).
|
||||
*
|
||||
* @param params An object with a `foundProps` record mapping each flagged path to its resolved type. For a
|
||||
* well-defined type with no issues, pass `{foundProps: {}}`.
|
||||
* @returns true
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* type BadType = {a: any; nested: {b: never}; list: Array<{c: any}>}
|
||||
*
|
||||
* // \@ts-expect-error there are `any`/`never` paths, so you can't claim there are none.
|
||||
* expectTypeOf<BadType>().branded.inspect({foundProps: {}})
|
||||
*
|
||||
* // ...instead, enumerate them (the compiler reports the exact paths if this is wrong):
|
||||
* expectTypeOf<BadType>().branded.inspect({
|
||||
* foundProps: {
|
||||
* '.a': 'any',
|
||||
* '.nested.b': 'never',
|
||||
* '.list[number].c': 'any',
|
||||
* },
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* type GoodType = {b: boolean; c: string}
|
||||
*
|
||||
* expectTypeOf<GoodType>().branded.inspect({foundProps: {}})
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // search for `unknown` instead of `any`/`never`:
|
||||
* expectTypeOf<{u: unknown}>().branded.inspect<{findType: 'unknown'}>({foundProps: {'.u': 'unknown'}})
|
||||
* ```
|
||||
*/
|
||||
inspect: <PropNoteOptions extends Exclude<DeepBrandPropNotesOptions, DeepBrandOptions> = DeepBrandPropNotesOptionsDefaults>(params: {
|
||||
foundProps: DeepBrandPropNotes<Actual, Options & PropNoteOptions>;
|
||||
}) => true;
|
||||
configure<O extends DeepBrandOptions>(): Branded<Actual, O>;
|
||||
}
|
||||
/**
|
||||
* Represents the negative expectation type for the {@linkcode Actual} type.
|
||||
*/
|
||||
export interface NegativeExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {
|
||||
positive: false;
|
||||
}> {
|
||||
/**
|
||||
* Similar to jest's `expect(...).toMatchObject(...)` but for types.
|
||||
* Deeply "picks" the properties of the actual type based on the expected type, then performs a strict check to make sure the types match `Expected`.
|
||||
*
|
||||
* **Note**: optional properties on the {@linkcode Expected | expected type} are not allowed to be missing on the {@linkcode Actual | actual type}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchObjectType<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toMatchObjectType<{ a: number; c?: number }>()
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toMatchObjectType: <Expected>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Pick<Actual, keyof Actual & keyof Expected>, Expected>, false>) => true;
|
||||
/**
|
||||
* Check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toExtend<{ a: number }>()]
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).not.toExtend<{ b: number }>()
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toExtend<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true;
|
||||
toEqualTypeOf: {
|
||||
/**
|
||||
* Uses TypeScript's internal technique to check for type "identicalness".
|
||||
*
|
||||
* It will check if the types are fully equal to each other.
|
||||
* It will not fail if two objects have different values, but the same type.
|
||||
* It will fail however if an object is missing a property.
|
||||
*
|
||||
* **_Unexpected failure_**? For a more permissive but less performant
|
||||
* check that accommodates for equivalent intersection types,
|
||||
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
|
||||
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param value - The value to compare against the expected type.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected>(value: Expected & AValue, ...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>): true;
|
||||
/**
|
||||
* Uses TypeScript's internal technique to check for type "identicalness".
|
||||
*
|
||||
* It will check if the types are fully equal to each other.
|
||||
* It will not fail if two objects have different values, but the same type.
|
||||
* It will fail however if an object is missing a property.
|
||||
*
|
||||
* **_Unexpected failure_**? For a more permissive but less performant
|
||||
* check that accommodates for equivalent intersection types,
|
||||
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
|
||||
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
|
||||
*
|
||||
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
|
||||
*
|
||||
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>): true;
|
||||
};
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*/
|
||||
toMatchTypeOf: {
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of
|
||||
* {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()}
|
||||
* that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint
|
||||
* in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param value - The value to compare against the expected type.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
|
||||
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true;
|
||||
/**
|
||||
* @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead
|
||||
*
|
||||
* - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys
|
||||
* - Use {@linkcode toExtend} to check if your type extends the expected type
|
||||
*
|
||||
* A less strict version of
|
||||
* {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()}
|
||||
* that allows for extra properties.
|
||||
* This is roughly equivalent to an `extends` constraint
|
||||
* in a function type argument.
|
||||
*
|
||||
* @example
|
||||
* <caption>Using generic type argument syntax</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* <caption>Using inferred type syntax by passing a value</caption>
|
||||
* ```ts
|
||||
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
|
||||
* ```
|
||||
*
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true;
|
||||
};
|
||||
/**
|
||||
* Checks whether an object has a given property.
|
||||
*
|
||||
* @example
|
||||
* <caption>check that properties exist</caption>
|
||||
* ```ts
|
||||
* const obj = { a: 1, b: '' }
|
||||
*
|
||||
* expectTypeOf(obj).toHaveProperty('a')
|
||||
*
|
||||
* expectTypeOf(obj).not.toHaveProperty('c')
|
||||
* ```
|
||||
*
|
||||
* @param key - The property key to check for.
|
||||
* @param MISMATCH - The mismatch arguments.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toHaveProperty: <KeyType extends string | number | symbol>(key: KeyType, ...MISMATCH: MismatchArgs<Extends<KeyType, keyof Actual>, false>) => true;
|
||||
}
|
||||
/**
|
||||
* Represents a conditional type that selects either
|
||||
* {@linkcode PositiveExpectTypeOf} or {@linkcode NegativeExpectTypeOf} based
|
||||
* on the value of the `positive` property in the {@linkcode Options} type.
|
||||
*/
|
||||
export type ExpectTypeOf<Actual, Options extends {
|
||||
positive: boolean;
|
||||
}> = Options['positive'] extends true ? PositiveExpectTypeOf<Actual> : NegativeExpectTypeOf<Actual>;
|
||||
/**
|
||||
* Represents the base interface for the
|
||||
* {@linkcode expectTypeOf()} function.
|
||||
* Provides a set of assertion methods to perform type checks on a value.
|
||||
*/
|
||||
export interface BaseExpectTypeOf<Actual, Options extends {
|
||||
positive: boolean;
|
||||
}> {
|
||||
/**
|
||||
* Checks whether the type of the value is `any`.
|
||||
*/
|
||||
toBeAny: Scolder<ExpectAny<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `unknown`.
|
||||
*/
|
||||
toBeUnknown: Scolder<ExpectUnknown<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `never`.
|
||||
*/
|
||||
toBeNever: Scolder<ExpectNever<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `function`.
|
||||
*/
|
||||
toBeFunction: Scolder<ExpectFunction<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `object`.
|
||||
*/
|
||||
toBeObject: Scolder<ExpectObject<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is an {@linkcode Array}.
|
||||
*/
|
||||
toBeArray: Scolder<ExpectArray<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `number`.
|
||||
*/
|
||||
toBeNumber: Scolder<ExpectNumber<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `string`.
|
||||
*/
|
||||
toBeString: Scolder<ExpectString<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `boolean`.
|
||||
*/
|
||||
toBeBoolean: Scolder<ExpectBoolean<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `void`.
|
||||
*/
|
||||
toBeVoid: Scolder<ExpectVoid<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `symbol`.
|
||||
*/
|
||||
toBeSymbol: Scolder<ExpectSymbol<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `null`.
|
||||
*/
|
||||
toBeNull: Scolder<ExpectNull<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `undefined`.
|
||||
*/
|
||||
toBeUndefined: Scolder<ExpectUndefined<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is `null` or `undefined`.
|
||||
*/
|
||||
toBeNullable: Scolder<ExpectNullable<Actual>, Options>;
|
||||
/**
|
||||
* Transform that type of the value via a callback.
|
||||
*
|
||||
* @param fn - A callback that transforms the input value. Note that this function is not actually called - it's only used for type inference.
|
||||
* @returns A new type which can be used for further assertions.
|
||||
*/
|
||||
map: <T>(fn: (value: Actual) => T) => ExpectTypeOf<T, Options>;
|
||||
/**
|
||||
* Checks whether the type of the value is **`bigint`**.
|
||||
*
|
||||
* @example
|
||||
* <caption>#### Distinguish between **`number`** and **`bigint`**</caption>
|
||||
*
|
||||
* ```ts
|
||||
* import { expectTypeOf } from 'expect-type'
|
||||
*
|
||||
* const aVeryBigInteger = 10n ** 100n
|
||||
*
|
||||
* expectTypeOf(aVeryBigInteger).not.toBeNumber()
|
||||
*
|
||||
* expectTypeOf(aVeryBigInteger).toBeBigInt()
|
||||
* ```
|
||||
*
|
||||
* @since 1.1.0
|
||||
*/
|
||||
toBeBigInt: Scolder<ExpectBigInt<Actual>, Options>;
|
||||
/**
|
||||
* Checks whether a function is callable with the given parameters.
|
||||
*
|
||||
* __Note__: You cannot negate this assertion with
|
||||
* {@linkcode PositiveExpectTypeOf.not | .not}, you need to use
|
||||
* `ts-expect-error` instead.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const f = (a: number) => [a, a]
|
||||
*
|
||||
* expectTypeOf(f).toBeCallableWith(1)
|
||||
* ```
|
||||
*
|
||||
* __Known Limitation__: This assertion will likely fail if you try to use it
|
||||
* with a generic function or an overload.
|
||||
* @see {@link https://github.com/mmkal/expect-type/issues/50 | This issue} for an example and a workaround.
|
||||
*
|
||||
* @param args - The arguments to check for callability.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toBeCallableWith: Options['positive'] extends true ? <Args extends OverloadParameters<Actual>>(...args: Args) => ExpectTypeOf<OverloadsNarrowedByParameters<Actual, Args>, Options> : never;
|
||||
/**
|
||||
* Checks whether a class is constructible with the given parameters.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf(Date).toBeConstructibleWith('1970')
|
||||
*
|
||||
* expectTypeOf(Date).toBeConstructibleWith(0)
|
||||
*
|
||||
* expectTypeOf(Date).toBeConstructibleWith(new Date())
|
||||
*
|
||||
* expectTypeOf(Date).toBeConstructibleWith()
|
||||
* ```
|
||||
*
|
||||
* @param args - The arguments to check for constructibility.
|
||||
* @returns `true`.
|
||||
*/
|
||||
toBeConstructibleWith: Options['positive'] extends true ? <Args extends ConstructorOverloadParameters<Actual>>(...args: Args) => true : never;
|
||||
/**
|
||||
* Equivalent to the {@linkcode Extract} utility type.
|
||||
* Helps narrow down complex union types.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
|
||||
*
|
||||
* interface CSSProperties {
|
||||
* margin?: string
|
||||
* padding?: string
|
||||
* }
|
||||
*
|
||||
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
|
||||
* return {}
|
||||
* }
|
||||
*
|
||||
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
|
||||
*
|
||||
* expectTypeOf(getResponsiveProp(cssProperties))
|
||||
* .extract<{ xs?: any }>() // extracts the last type from a union
|
||||
* .toEqualTypeOf<{
|
||||
* xs?: CSSProperties
|
||||
* sm?: CSSProperties
|
||||
* md?: CSSProperties
|
||||
* }>()
|
||||
*
|
||||
* expectTypeOf(getResponsiveProp(cssProperties))
|
||||
* .extract<unknown[]>() // extracts an array from a union
|
||||
* .toEqualTypeOf<CSSProperties[]>()
|
||||
* ```
|
||||
*
|
||||
* __Note__: If no type is found in the union, it will return `never`.
|
||||
*
|
||||
* @param v - The type to extract from the union.
|
||||
* @returns The type after extracting the type from the union.
|
||||
*/
|
||||
extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode Exclude} utility type.
|
||||
* Removes types from a union.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
|
||||
*
|
||||
* interface CSSProperties {
|
||||
* margin?: string
|
||||
* padding?: string
|
||||
* }
|
||||
*
|
||||
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
|
||||
* return {}
|
||||
* }
|
||||
*
|
||||
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
|
||||
*
|
||||
* expectTypeOf(getResponsiveProp(cssProperties))
|
||||
* .exclude<unknown[]>()
|
||||
* .exclude<{ xs?: unknown }>() // or just `.exclude<unknown[] | { xs?: unknown }>()`
|
||||
* .toEqualTypeOf<CSSProperties>()
|
||||
* ```
|
||||
*/
|
||||
exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode Pick} utility type.
|
||||
* Helps select a subset of properties from an object type.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* interface Person {
|
||||
* name: string
|
||||
* age: number
|
||||
* }
|
||||
*
|
||||
* expectTypeOf<Person>()
|
||||
* .pick<'name'>()
|
||||
* .toEqualTypeOf<{ name: string }>()
|
||||
* ```
|
||||
*
|
||||
* @param keyToPick - The property key to pick.
|
||||
* @returns The type after picking the property.
|
||||
*/
|
||||
pick: <KeyToPick extends keyof Actual>(keyToPick?: KeyToPick) => ExpectTypeOf<Pick<Actual, KeyToPick>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode Omit} utility type.
|
||||
* Helps remove a subset of properties from an object type.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* interface Person {
|
||||
* name: string
|
||||
* age: number
|
||||
* }
|
||||
*
|
||||
* expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{ age: number }>()
|
||||
* ```
|
||||
*
|
||||
* @param keyToOmit - The property key to omit.
|
||||
* @returns The type after omitting the property.
|
||||
*/
|
||||
omit: <KeyToOmit extends keyof Actual | (PropertyKey & Record<never, never>)>(keyToOmit?: KeyToOmit) => ExpectTypeOf<Omit<Actual, KeyToOmit>, Options>;
|
||||
/**
|
||||
* Extracts a certain function argument with `.parameter(number)` call to
|
||||
* perform other assertions on it.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* function foo(a: number, b: string) {
|
||||
* return [a, b]
|
||||
* }
|
||||
*
|
||||
* expectTypeOf(foo).parameter(0).toBeNumber()
|
||||
*
|
||||
* expectTypeOf(foo).parameter(1).toBeString()
|
||||
* ```
|
||||
*
|
||||
* @param index - The index of the parameter to extract.
|
||||
* @returns The extracted parameter type.
|
||||
*/
|
||||
parameter: <Index extends number>(index: Index) => ExpectTypeOf<OverloadParameters<Actual>[Index], Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode Parameters} utility type.
|
||||
* Extracts function parameters to perform assertions on its value.
|
||||
* Parameters are returned as an array.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* function noParam() {}
|
||||
*
|
||||
* function hasParam(s: string) {}
|
||||
*
|
||||
* expectTypeOf(noParam).parameters.toEqualTypeOf<[]>()
|
||||
*
|
||||
* expectTypeOf(hasParam).parameters.toEqualTypeOf<[string]>()
|
||||
* ```
|
||||
*/
|
||||
parameters: ExpectTypeOf<OverloadParameters<Actual>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode ConstructorParameters} utility type.
|
||||
* Extracts constructor parameters as an array of values and
|
||||
* perform assertions on them with this method.
|
||||
*
|
||||
* For overloaded constructors it will return a union of all possible parameter-tuples.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf(Date).constructorParameters.toEqualTypeOf<
|
||||
* [] | [string | number | Date]
|
||||
* >()
|
||||
* ```
|
||||
*/
|
||||
constructorParameters: ExpectTypeOf<ConstructorOverloadParameters<Actual>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode ThisParameterType} utility type.
|
||||
* Extracts the `this` parameter of a function to
|
||||
* perform assertions on its value.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* function greet(this: { name: string }, message: string) {
|
||||
* return `Hello ${this.name}, here's your message: ${message}`
|
||||
* }
|
||||
*
|
||||
* expectTypeOf(greet).thisParameter.toEqualTypeOf<{ name: string }>()
|
||||
* ```
|
||||
*/
|
||||
thisParameter: ExpectTypeOf<OverloadThisParameterTypes<Actual>, Options>;
|
||||
/**
|
||||
* Equivalent to the {@linkcode InstanceType} utility type.
|
||||
* Extracts the instance type of a class to perform assertions on.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf(Date).instance.toHaveProperty('toISOString')
|
||||
* ```
|
||||
*/
|
||||
instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf<I, Options> : never;
|
||||
/**
|
||||
* Equivalent to the {@linkcode ReturnType} utility type.
|
||||
* Extracts the return type of a function.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf(() => {}).returns.toBeVoid()
|
||||
*
|
||||
* expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2])
|
||||
* ```
|
||||
*/
|
||||
returns: Actual extends Function ? ExpectTypeOf<OverloadReturnTypes<Actual>, Options> : never;
|
||||
/**
|
||||
* Extracts resolved value of a Promise,
|
||||
* so you can perform other assertions on it.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* async function asyncFunc() {
|
||||
* return 123
|
||||
* }
|
||||
*
|
||||
* expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
|
||||
*
|
||||
* expectTypeOf(Promise.resolve('string')).resolves.toBeString()
|
||||
* ```
|
||||
*
|
||||
* Type Equivalent:
|
||||
* ```ts
|
||||
* type Resolves<PromiseType> = PromiseType extends PromiseLike<infer ResolvedType>
|
||||
* ? ResolvedType
|
||||
* : never
|
||||
* ```
|
||||
*/
|
||||
resolves: Actual extends PromiseLike<infer ResolvedType> ? ExpectTypeOf<ResolvedType, Options> : never;
|
||||
/**
|
||||
* Extracts array item type to perform assertions on.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* expectTypeOf([1, 2, 3]).items.toEqualTypeOf<number>()
|
||||
*
|
||||
* expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf<string>()
|
||||
* ```
|
||||
*
|
||||
* __Type Equivalent__:
|
||||
* ```ts
|
||||
* type Items<ArrayType> = ArrayType extends ArrayLike<infer ItemType>
|
||||
* ? ItemType
|
||||
* : never
|
||||
* ```
|
||||
*/
|
||||
items: Actual extends ArrayLike<infer ItemType> ? ExpectTypeOf<ItemType, Options> : never;
|
||||
/**
|
||||
* Extracts the type guarded by a function to perform assertions on.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* function isString(v: any): v is string {
|
||||
* return typeof v === 'string'
|
||||
* }
|
||||
*
|
||||
* expectTypeOf(isString).guards.toBeString()
|
||||
* ```
|
||||
*/
|
||||
guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf<T, Options> : never;
|
||||
/**
|
||||
* Extracts the type asserted by a function to perform assertions on.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* function assertNumber(v: any): asserts v is number {
|
||||
* if (typeof v !== 'number')
|
||||
* throw new TypeError('Nope !')
|
||||
* }
|
||||
*
|
||||
* expectTypeOf(assertNumber).asserts.toBeNumber()
|
||||
* ```
|
||||
*/
|
||||
asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf<T, Options> : never;
|
||||
}
|
||||
/**
|
||||
* Represents a function that allows asserting the expected type of a value.
|
||||
*/
|
||||
export type _ExpectTypeOf = {
|
||||
/**
|
||||
* Asserts the expected type of a value.
|
||||
*
|
||||
* @param actual - The actual value being asserted.
|
||||
* @returns An object representing the expected type assertion.
|
||||
*/
|
||||
<Actual>(actual: Actual): ExpectTypeOf<Actual, {
|
||||
positive: true;
|
||||
branded: false;
|
||||
}>;
|
||||
/**
|
||||
* Asserts the expected type of a value without providing an actual value.
|
||||
*
|
||||
* @returns An object representing the expected type assertion.
|
||||
*/
|
||||
<Actual>(): ExpectTypeOf<Actual, {
|
||||
positive: true;
|
||||
branded: false;
|
||||
}>;
|
||||
};
|
||||
/**
|
||||
* Similar to Jest's `expect`, but with type-awareness.
|
||||
* Gives you access to a number of type-matchers that let you make assertions about the
|
||||
* form of a reference or generic type parameter.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { foo, bar } from '../foo'
|
||||
* import { expectTypeOf } from 'expect-type'
|
||||
*
|
||||
* test('foo types', () => {
|
||||
* // make sure `foo` has type { a: number }
|
||||
* expectTypeOf(foo).toMatchTypeOf({ a: 1 })
|
||||
* expectTypeOf(foo).toHaveProperty('a').toBeNumber()
|
||||
*
|
||||
* // make sure `bar` is a function taking a string:
|
||||
* expectTypeOf(bar).parameter(0).toBeString()
|
||||
* expectTypeOf(bar).returns.not.toBeAny()
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @description
|
||||
* See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
|
||||
*/
|
||||
export declare const expectTypeOf: _ExpectTypeOf;
|
||||
@@ -0,0 +1 @@
|
||||
export type { DebugLevel, EcmaVersion, ParserOptions, SourceType, } from '@typescript-eslint/types';
|
||||
@@ -0,0 +1,93 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-non-null-assertion',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Disallow non-null assertions using the `!` postfix operator',
|
||||
recommended: 'strict',
|
||||
},
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
noNonNull: 'Forbidden non-null assertion.',
|
||||
suggestOptionalChain: 'Consider using the optional chain operator `?.` instead. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
return {
|
||||
TSNonNullExpression(node) {
|
||||
const suggest = [];
|
||||
// it always exists in non-null assertion
|
||||
const nonNullOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.expression, util_1.isNonNullAssertionPunctuator), util_1.NullThrowsReasons.MissingToken('!', 'expression'));
|
||||
function replaceTokenWithOptional() {
|
||||
return fixer => fixer.replaceText(nonNullOperator, '?.');
|
||||
}
|
||||
function removeToken() {
|
||||
return fixer => fixer.remove(nonNullOperator);
|
||||
}
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.MemberExpression &&
|
||||
node.parent.object === node &&
|
||||
!(0, util_1.isAssignee)(node.parent)) {
|
||||
if (!node.parent.optional) {
|
||||
if (node.parent.computed) {
|
||||
// it is x![y]?.z
|
||||
suggest.push({
|
||||
messageId: 'suggestOptionalChain',
|
||||
fix: replaceTokenWithOptional(),
|
||||
});
|
||||
}
|
||||
else {
|
||||
// it is x!.y?.z
|
||||
suggest.push({
|
||||
messageId: 'suggestOptionalChain',
|
||||
fix(fixer) {
|
||||
// x!.y?.z
|
||||
// ^ punctuator
|
||||
const punctuator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(nonNullOperator), util_1.NullThrowsReasons.MissingToken('.', '!'));
|
||||
return [
|
||||
fixer.remove(nonNullOperator),
|
||||
fixer.insertTextBefore(punctuator, '?'),
|
||||
];
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
else {
|
||||
// it is x!?.[y].z or x!?.y.z
|
||||
suggest.push({
|
||||
messageId: 'suggestOptionalChain',
|
||||
fix: removeToken(),
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (node.parent.type === utils_1.AST_NODE_TYPES.CallExpression &&
|
||||
node.parent.callee === node) {
|
||||
if (!node.parent.optional) {
|
||||
// it is x.y?.z!()
|
||||
suggest.push({
|
||||
messageId: 'suggestOptionalChain',
|
||||
fix: replaceTokenWithOptional(),
|
||||
});
|
||||
}
|
||||
else {
|
||||
// it is x.y.z!?.()
|
||||
suggest.push({
|
||||
messageId: 'suggestOptionalChain',
|
||||
fix: removeToken(),
|
||||
});
|
||||
}
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noNonNull',
|
||||
suggest,
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
"use strict";
|
||||
|
||||
function _inherits_loose(subClass, superClass) {
|
||||
subClass.prototype = Object.create(superClass.prototype);
|
||||
subClass.prototype.constructor = subClass;
|
||||
subClass.__proto__ = superClass;
|
||||
}
|
||||
exports._ = _inherits_loose;
|
||||
@@ -0,0 +1,42 @@
|
||||
'use strict'
|
||||
|
||||
let Warning = require('./warning')
|
||||
|
||||
class Result {
|
||||
get content() {
|
||||
return this.css
|
||||
}
|
||||
|
||||
constructor(processor, root, opts) {
|
||||
this.processor = processor
|
||||
this.messages = []
|
||||
this.root = root
|
||||
this.opts = opts
|
||||
this.css = ''
|
||||
this.map = undefined
|
||||
}
|
||||
|
||||
toString() {
|
||||
return this.css
|
||||
}
|
||||
|
||||
warn(text, opts = {}) {
|
||||
if (!opts.plugin) {
|
||||
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
|
||||
opts.plugin = this.lastPlugin.postcssPlugin
|
||||
}
|
||||
}
|
||||
|
||||
let warning = new Warning(text, opts)
|
||||
this.messages.push(warning)
|
||||
|
||||
return warning
|
||||
}
|
||||
|
||||
warnings() {
|
||||
return this.messages.filter(i => i.type === 'warning')
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Result
|
||||
Result.default = Result
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,MAAM,EAAE,GAKJ,CAAC"}
|
||||
@@ -0,0 +1,419 @@
|
||||
2.20.3 / 2019-10-11
|
||||
==================
|
||||
|
||||
* Support Node.js 0.10 (Revert #1059)
|
||||
* Ran "npm unpublish commander@2.20.2". There is no 2.20.2.
|
||||
|
||||
2.20.1 / 2019-09-29
|
||||
==================
|
||||
|
||||
* Improve executable subcommand tracking
|
||||
* Update dev dependencies
|
||||
|
||||
2.20.0 / 2019-04-02
|
||||
==================
|
||||
|
||||
* fix: resolve symbolic links completely when hunting for subcommands (#935)
|
||||
* Update index.d.ts (#930)
|
||||
* Update Readme.md (#924)
|
||||
* Remove --save option as it isn't required anymore (#918)
|
||||
* Add link to the license file (#900)
|
||||
* Added example of receiving args from options (#858)
|
||||
* Added missing semicolon (#882)
|
||||
* Add extension to .eslintrc (#876)
|
||||
|
||||
2.19.0 / 2018-10-02
|
||||
==================
|
||||
|
||||
* Removed newline after Options and Commands headers (#864)
|
||||
* Bugfix - Error output (#862)
|
||||
* Fix to change default value to string (#856)
|
||||
|
||||
2.18.0 / 2018-09-07
|
||||
==================
|
||||
|
||||
* Standardize help output (#853)
|
||||
* chmod 644 travis.yml (#851)
|
||||
* add support for execute typescript subcommand via ts-node (#849)
|
||||
|
||||
2.17.1 / 2018-08-07
|
||||
==================
|
||||
|
||||
* Fix bug in command emit (#844)
|
||||
|
||||
2.17.0 / 2018-08-03
|
||||
==================
|
||||
|
||||
* fixed newline output after help information (#833)
|
||||
* Fix to emit the action even without command (#778)
|
||||
* npm update (#823)
|
||||
|
||||
2.16.0 / 2018-06-29
|
||||
==================
|
||||
|
||||
* Remove Makefile and `test/run` (#821)
|
||||
* Make 'npm test' run on Windows (#820)
|
||||
* Add badge to display install size (#807)
|
||||
* chore: cache node_modules (#814)
|
||||
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
|
||||
* fixed typo in readme (#812)
|
||||
* Fix types (#804)
|
||||
* Update eslint to resolve vulnerabilities in lodash (#799)
|
||||
* updated readme with custom event listeners. (#791)
|
||||
* fix tests (#794)
|
||||
|
||||
2.15.0 / 2018-03-07
|
||||
==================
|
||||
|
||||
* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
|
||||
* Arguments description
|
||||
|
||||
2.14.1 / 2018-02-07
|
||||
==================
|
||||
|
||||
* Fix typing of help function
|
||||
|
||||
2.14.0 / 2018-02-05
|
||||
==================
|
||||
|
||||
* only register the option:version event once
|
||||
* Fixes issue #727: Passing empty string for option on command is set to undefined
|
||||
* enable eqeqeq rule
|
||||
* resolves #754 add linter configuration to project
|
||||
* resolves #560 respect custom name for version option
|
||||
* document how to override the version flag
|
||||
* document using options per command
|
||||
|
||||
2.13.0 / 2018-01-09
|
||||
==================
|
||||
|
||||
* Do not print default for --no-
|
||||
* remove trailing spaces in command help
|
||||
* Update CI's Node.js to LTS and latest version
|
||||
* typedefs: Command and Option types added to commander namespace
|
||||
|
||||
2.12.2 / 2017-11-28
|
||||
==================
|
||||
|
||||
* fix: typings are not shipped
|
||||
|
||||
2.12.1 / 2017-11-23
|
||||
==================
|
||||
|
||||
* Move @types/node to dev dependency
|
||||
|
||||
2.12.0 / 2017-11-22
|
||||
==================
|
||||
|
||||
* add attributeName() method to Option objects
|
||||
* Documentation updated for options with --no prefix
|
||||
* typings: `outputHelp` takes a string as the first parameter
|
||||
* typings: use overloads
|
||||
* feat(typings): update to match js api
|
||||
* Print default value in option help
|
||||
* Fix translation error
|
||||
* Fail when using same command and alias (#491)
|
||||
* feat(typings): add help callback
|
||||
* fix bug when description is add after command with options (#662)
|
||||
* Format js code
|
||||
* Rename History.md to CHANGELOG.md (#668)
|
||||
* feat(typings): add typings to support TypeScript (#646)
|
||||
* use current node
|
||||
|
||||
2.11.0 / 2017-07-03
|
||||
==================
|
||||
|
||||
* Fix help section order and padding (#652)
|
||||
* feature: support for signals to subcommands (#632)
|
||||
* Fixed #37, --help should not display first (#447)
|
||||
* Fix translation errors. (#570)
|
||||
* Add package-lock.json
|
||||
* Remove engines
|
||||
* Upgrade package version
|
||||
* Prefix events to prevent conflicts between commands and options (#494)
|
||||
* Removing dependency on graceful-readlink
|
||||
* Support setting name in #name function and make it chainable
|
||||
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
|
||||
* Updated link to ruby commander in readme files
|
||||
|
||||
2.10.0 / 2017-06-19
|
||||
==================
|
||||
|
||||
* Update .travis.yml. drop support for older node.js versions.
|
||||
* Fix require arguments in README.md
|
||||
* On SemVer you do not start from 0.0.1
|
||||
* Add missing semi colon in readme
|
||||
* Add save param to npm install
|
||||
* node v6 travis test
|
||||
* Update Readme_zh-CN.md
|
||||
* Allow literal '--' to be passed-through as an argument
|
||||
* Test subcommand alias help
|
||||
* link build badge to master branch
|
||||
* Support the alias of Git style sub-command
|
||||
* added keyword commander for better search result on npm
|
||||
* Fix Sub-Subcommands
|
||||
* test node.js stable
|
||||
* Fixes TypeError when a command has an option called `--description`
|
||||
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
|
||||
* Add chinese Readme file
|
||||
|
||||
2.9.0 / 2015-10-13
|
||||
==================
|
||||
|
||||
* Add option `isDefault` to set default subcommand #415 @Qix-
|
||||
* Add callback to allow filtering or post-processing of help text #434 @djulien
|
||||
* Fix `undefined` text in help information close #414 #416 @zhiyelee
|
||||
|
||||
2.8.1 / 2015-04-22
|
||||
==================
|
||||
|
||||
* Back out `support multiline description` Close #396 #397
|
||||
|
||||
2.8.0 / 2015-04-07
|
||||
==================
|
||||
|
||||
* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
|
||||
* Fix bug in Git-style sub-commands #372 @zhiyelee
|
||||
* Allow commands to be hidden from help #383 @tonylukasavage
|
||||
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
|
||||
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
|
||||
* Support multiline descriptions #208 @zxqfox
|
||||
|
||||
2.7.1 / 2015-03-11
|
||||
==================
|
||||
|
||||
* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
|
||||
|
||||
2.7.0 / 2015-03-09
|
||||
==================
|
||||
|
||||
* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
|
||||
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
|
||||
* Add support for camelCase on `opts()`. Close #353 @nkzawa
|
||||
* Add node.js 0.12 and io.js to travis.yml
|
||||
* Allow RegEx options. #337 @palanik
|
||||
* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
|
||||
* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
|
||||
|
||||
2.6.0 / 2014-12-30
|
||||
==================
|
||||
|
||||
* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
|
||||
* Add application description to the help msg. Close #112 @dalssoft
|
||||
|
||||
2.5.1 / 2014-12-15
|
||||
==================
|
||||
|
||||
* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
|
||||
|
||||
2.5.0 / 2014-10-24
|
||||
==================
|
||||
|
||||
* add support for variadic arguments. Closes #277 @whitlockjc
|
||||
|
||||
2.4.0 / 2014-10-17
|
||||
==================
|
||||
|
||||
* fixed a bug on executing the coercion function of subcommands option. Closes #270
|
||||
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
|
||||
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
|
||||
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
|
||||
* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr
|
||||
|
||||
2.3.0 / 2014-07-16
|
||||
==================
|
||||
|
||||
* add command alias'. Closes PR #210
|
||||
* fix: Typos. Closes #99
|
||||
* fix: Unused fs module. Closes #217
|
||||
|
||||
2.2.0 / 2014-03-29
|
||||
==================
|
||||
|
||||
* add passing of previous option value
|
||||
* fix: support subcommands on windows. Closes #142
|
||||
* Now the defaultValue passed as the second argument of the coercion function.
|
||||
|
||||
2.1.0 / 2013-11-21
|
||||
==================
|
||||
|
||||
* add: allow cflag style option params, unit test, fixes #174
|
||||
|
||||
2.0.0 / 2013-07-18
|
||||
==================
|
||||
|
||||
* remove input methods (.prompt, .confirm, etc)
|
||||
|
||||
1.3.2 / 2013-07-18
|
||||
==================
|
||||
|
||||
* add support for sub-commands to co-exist with the original command
|
||||
|
||||
1.3.1 / 2013-07-18
|
||||
==================
|
||||
|
||||
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
|
||||
|
||||
1.3.0 / 2013-07-09
|
||||
==================
|
||||
|
||||
* add EACCES error handling
|
||||
* fix sub-command --help
|
||||
|
||||
1.2.0 / 2013-06-13
|
||||
==================
|
||||
|
||||
* allow "-" hyphen as an option argument
|
||||
* support for RegExp coercion
|
||||
|
||||
1.1.1 / 2012-11-20
|
||||
==================
|
||||
|
||||
* add more sub-command padding
|
||||
* fix .usage() when args are present. Closes #106
|
||||
|
||||
1.1.0 / 2012-11-16
|
||||
==================
|
||||
|
||||
* add git-style executable subcommand support. Closes #94
|
||||
|
||||
1.0.5 / 2012-10-09
|
||||
==================
|
||||
|
||||
* fix `--name` clobbering. Closes #92
|
||||
* fix examples/help. Closes #89
|
||||
|
||||
1.0.4 / 2012-09-03
|
||||
==================
|
||||
|
||||
* add `outputHelp()` method.
|
||||
|
||||
1.0.3 / 2012-08-30
|
||||
==================
|
||||
|
||||
* remove invalid .version() defaulting
|
||||
|
||||
1.0.2 / 2012-08-24
|
||||
==================
|
||||
|
||||
* add `--foo=bar` support [arv]
|
||||
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
|
||||
|
||||
1.0.1 / 2012-08-03
|
||||
==================
|
||||
|
||||
* fix issue #56
|
||||
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
|
||||
|
||||
1.0.0 / 2012-07-05
|
||||
==================
|
||||
|
||||
* add support for optional option descriptions
|
||||
* add defaulting of `.version()` to package.json's version
|
||||
|
||||
0.6.1 / 2012-06-01
|
||||
==================
|
||||
|
||||
* Added: append (yes or no) on confirmation
|
||||
* Added: allow node.js v0.7.x
|
||||
|
||||
0.6.0 / 2012-04-10
|
||||
==================
|
||||
|
||||
* Added `.prompt(obj, callback)` support. Closes #49
|
||||
* Added default support to .choose(). Closes #41
|
||||
* Fixed the choice example
|
||||
|
||||
0.5.1 / 2011-12-20
|
||||
==================
|
||||
|
||||
* Fixed `password()` for recent nodes. Closes #36
|
||||
|
||||
0.5.0 / 2011-12-04
|
||||
==================
|
||||
|
||||
* Added sub-command option support [itay]
|
||||
|
||||
0.4.3 / 2011-12-04
|
||||
==================
|
||||
|
||||
* Fixed custom help ordering. Closes #32
|
||||
|
||||
0.4.2 / 2011-11-24
|
||||
==================
|
||||
|
||||
* Added travis support
|
||||
* Fixed: line-buffered input automatically trimmed. Closes #31
|
||||
|
||||
0.4.1 / 2011-11-18
|
||||
==================
|
||||
|
||||
* Removed listening for "close" on --help
|
||||
|
||||
0.4.0 / 2011-11-15
|
||||
==================
|
||||
|
||||
* Added support for `--`. Closes #24
|
||||
|
||||
0.3.3 / 2011-11-14
|
||||
==================
|
||||
|
||||
* Fixed: wait for close event when writing help info [Jerry Hamlet]
|
||||
|
||||
0.3.2 / 2011-11-01
|
||||
==================
|
||||
|
||||
* Fixed long flag definitions with values [felixge]
|
||||
|
||||
0.3.1 / 2011-10-31
|
||||
==================
|
||||
|
||||
* Changed `--version` short flag to `-V` from `-v`
|
||||
* Changed `.version()` so it's configurable [felixge]
|
||||
|
||||
0.3.0 / 2011-10-31
|
||||
==================
|
||||
|
||||
* Added support for long flags only. Closes #18
|
||||
|
||||
0.2.1 / 2011-10-24
|
||||
==================
|
||||
|
||||
* "node": ">= 0.4.x < 0.7.0". Closes #20
|
||||
|
||||
0.2.0 / 2011-09-26
|
||||
==================
|
||||
|
||||
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
|
||||
|
||||
0.1.0 / 2011-08-24
|
||||
==================
|
||||
|
||||
* Added support for custom `--help` output
|
||||
|
||||
0.0.5 / 2011-08-18
|
||||
==================
|
||||
|
||||
* Changed: when the user enters nothing prompt for password again
|
||||
* Fixed issue with passwords beginning with numbers [NuckChorris]
|
||||
|
||||
0.0.4 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Fixed `Commander#args`
|
||||
|
||||
0.0.3 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Added default option value support
|
||||
|
||||
0.0.2 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Added mask support to `Command#password(str[, mask], fn)`
|
||||
* Added `Command#password(str, fn)`
|
||||
|
||||
0.0.1 / 2010-01-03
|
||||
==================
|
||||
|
||||
* Initial release
|
||||
@@ -0,0 +1,13 @@
|
||||
Copyright (c) 2014-2018, Matteo Collina <hello@matteocollina.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
Reference in New Issue
Block a user