WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag when using multiline strings
|
||||
* @author Ilya Volodin
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "Disallow multiline strings",
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-multi-str",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
multilineString:
|
||||
"Multiline support is limited to browsers supporting ES5 only.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
/**
|
||||
* Determines if a given node is part of JSX syntax.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} True if the node is a JSX node, false if not.
|
||||
* @private
|
||||
*/
|
||||
function isJSXElement(node) {
|
||||
return node.type.indexOf("JSX") === 0;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public API
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
Literal(node) {
|
||||
if (
|
||||
astUtils.LINEBREAK_MATCHER.test(node.raw) &&
|
||||
!isJSXElement(node.parent)
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "multilineString",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-unnecessary-qualifier',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow unnecessary namespace qualifiers',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
unnecessaryQualifier: "Qualifier is unnecessary since '{{ name }}' is in scope.",
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
const namespacesInScope = [];
|
||||
let currentFailedNamespaceExpression = null;
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const esTreeNodeToTSNodeMap = services.esTreeNodeToTSNodeMap;
|
||||
const checker = services.program.getTypeChecker();
|
||||
function tryGetAliasedSymbol(symbol, checker) {
|
||||
return tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)
|
||||
? checker.getAliasedSymbol(symbol)
|
||||
: null;
|
||||
}
|
||||
function symbolIsNamespaceInScope(symbol) {
|
||||
const symbolDeclarations = symbol.getDeclarations() ?? [];
|
||||
if (symbolDeclarations.some(decl => namespacesInScope.some(ns => ns === decl))) {
|
||||
return true;
|
||||
}
|
||||
const alias = tryGetAliasedSymbol(symbol, checker);
|
||||
return alias != null && symbolIsNamespaceInScope(alias);
|
||||
}
|
||||
function getSymbolInScope(node, flags, name) {
|
||||
const scope = checker.getSymbolsInScope(node, flags);
|
||||
return scope.find(scopeSymbol => scopeSymbol.name === name);
|
||||
}
|
||||
function symbolsAreEqual(accessed, inScope) {
|
||||
return accessed === checker.getExportSymbolOfSymbol(inScope);
|
||||
}
|
||||
function qualifierIsUnnecessary(qualifier, name) {
|
||||
const namespaceSymbol = services.getSymbolAtLocation(qualifier);
|
||||
if (namespaceSymbol == null ||
|
||||
!symbolIsNamespaceInScope(namespaceSymbol)) {
|
||||
return false;
|
||||
}
|
||||
const accessedSymbol = services.getSymbolAtLocation(name);
|
||||
if (accessedSymbol == null) {
|
||||
return false;
|
||||
}
|
||||
// If the symbol in scope is different, the qualifier is necessary.
|
||||
const tsQualifier = esTreeNodeToTSNodeMap.get(qualifier);
|
||||
const fromScope = getSymbolInScope(tsQualifier, accessedSymbol.flags, context.sourceCode.getText(name));
|
||||
return !!fromScope && symbolsAreEqual(accessedSymbol, fromScope);
|
||||
}
|
||||
function visitNamespaceAccess(node, qualifier, name) {
|
||||
// Only look for nested qualifier errors if we didn't already fail on the outer qualifier.
|
||||
if (!currentFailedNamespaceExpression &&
|
||||
qualifierIsUnnecessary(qualifier, name)) {
|
||||
currentFailedNamespaceExpression = node;
|
||||
context.report({
|
||||
node: qualifier,
|
||||
messageId: 'unnecessaryQualifier',
|
||||
data: {
|
||||
name: context.sourceCode.getText(name),
|
||||
},
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([qualifier.range[0], name.range[0]]);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
function enterDeclaration(node) {
|
||||
namespacesInScope.push(esTreeNodeToTSNodeMap.get(node));
|
||||
}
|
||||
function exitDeclaration() {
|
||||
namespacesInScope.pop();
|
||||
}
|
||||
function resetCurrentNamespaceExpression(node) {
|
||||
if (node === currentFailedNamespaceExpression) {
|
||||
currentFailedNamespaceExpression = null;
|
||||
}
|
||||
}
|
||||
function isPropertyAccessExpression(node) {
|
||||
return node.type === utils_1.AST_NODE_TYPES.MemberExpression && !node.computed;
|
||||
}
|
||||
function isEntityNameExpression(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.Identifier ||
|
||||
(isPropertyAccessExpression(node) &&
|
||||
isEntityNameExpression(node.object)));
|
||||
}
|
||||
return {
|
||||
'ExportNamedDeclaration[declaration.type="TSEnumDeclaration"]': enterDeclaration,
|
||||
'ExportNamedDeclaration[declaration.type="TSEnumDeclaration"]:exit': exitDeclaration,
|
||||
'ExportNamedDeclaration[declaration.type="TSModuleDeclaration"]': enterDeclaration,
|
||||
'ExportNamedDeclaration[declaration.type="TSModuleDeclaration"]:exit': exitDeclaration,
|
||||
'MemberExpression:exit': resetCurrentNamespaceExpression,
|
||||
'MemberExpression[computed=false]'(node) {
|
||||
const property = node.property;
|
||||
if (isEntityNameExpression(node.object)) {
|
||||
visitNamespaceAccess(node, node.object, property);
|
||||
}
|
||||
},
|
||||
TSEnumDeclaration: enterDeclaration,
|
||||
'TSEnumDeclaration:exit': exitDeclaration,
|
||||
'TSModuleDeclaration:exit': exitDeclaration,
|
||||
'TSModuleDeclaration > TSModuleBlock'(node) {
|
||||
enterDeclaration(node.parent);
|
||||
},
|
||||
TSQualifiedName(node) {
|
||||
visitNamespaceAccess(node, node.left, node.right);
|
||||
},
|
||||
'TSQualifiedName:exit': resetCurrentNamespaceExpression,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { g as globalApis } from './constants.CPYnjOGj.js';
|
||||
import { i as index } from './index.DdgEv5B1.js';
|
||||
import './test.DNmyFkvJ.js';
|
||||
import '@vitest/runner';
|
||||
import '@vitest/utils/helpers';
|
||||
import '@vitest/utils/timers';
|
||||
import './benchmark.CX_oY03V.js';
|
||||
import '@vitest/runner/utils';
|
||||
import './utils.BX5Fg8C4.js';
|
||||
import '@vitest/expect';
|
||||
import '@vitest/utils/error';
|
||||
import 'pathe';
|
||||
import '@vitest/spy';
|
||||
import '@vitest/utils/offset';
|
||||
import '@vitest/utils/source-map';
|
||||
import './_commonjsHelpers.D26ty3Ew.js';
|
||||
import './rpc.MzXet3jl.js';
|
||||
import './index.Chj8NDwU.js';
|
||||
import '@vitest/snapshot';
|
||||
import './evaluatedModules.Dg1zASAC.js';
|
||||
import 'vite/module-runner';
|
||||
import 'expect-type';
|
||||
|
||||
function registerApiGlobally() {
|
||||
globalApis.forEach((api) => {
|
||||
// @ts-expect-error I know what I am doing :P
|
||||
globalThis[api] = index[api];
|
||||
});
|
||||
}
|
||||
|
||||
export { registerApiGlobally };
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_class_static_private_field_spec_get.js";
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* @fileoverview This file contains the types for the use-at-your-own-risk
|
||||
* entrypoint. It was initially extracted from the `@types/eslint` package.
|
||||
*/
|
||||
|
||||
/*
|
||||
* MIT License
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE
|
||||
*/
|
||||
|
||||
import { Rule } from "./index.js";
|
||||
|
||||
/** @deprecated */
|
||||
export const builtinRules: Map<string, Rule.RuleModule>;
|
||||
|
||||
/** @deprecated */
|
||||
export function shouldUseFlatConfig(): Promise<true>;
|
||||
@@ -0,0 +1,94 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PatternVisitor = void 0;
|
||||
const types_1 = require("@typescript-eslint/types");
|
||||
const VisitorBase_1 = require("./VisitorBase");
|
||||
class PatternVisitor extends VisitorBase_1.VisitorBase {
|
||||
#assignments = [];
|
||||
#callback;
|
||||
#restElements = [];
|
||||
#rootPattern;
|
||||
rightHandNodes = [];
|
||||
constructor(options, rootPattern, callback) {
|
||||
super(options);
|
||||
this.#rootPattern = rootPattern;
|
||||
this.#callback = callback;
|
||||
}
|
||||
static isPattern(node) {
|
||||
const nodeType = node.type;
|
||||
return (nodeType === types_1.AST_NODE_TYPES.Identifier ||
|
||||
nodeType === types_1.AST_NODE_TYPES.ObjectPattern ||
|
||||
nodeType === types_1.AST_NODE_TYPES.ArrayPattern ||
|
||||
nodeType === types_1.AST_NODE_TYPES.SpreadElement ||
|
||||
nodeType === types_1.AST_NODE_TYPES.RestElement ||
|
||||
nodeType === types_1.AST_NODE_TYPES.AssignmentPattern);
|
||||
}
|
||||
ArrayExpression(node) {
|
||||
node.elements.forEach(this.visit, this);
|
||||
}
|
||||
ArrayPattern(pattern) {
|
||||
for (const element of pattern.elements) {
|
||||
this.visit(element);
|
||||
}
|
||||
}
|
||||
AssignmentExpression(node) {
|
||||
this.#assignments.push(node);
|
||||
this.visit(node.left);
|
||||
this.rightHandNodes.push(node.right);
|
||||
this.#assignments.pop();
|
||||
}
|
||||
AssignmentPattern(pattern) {
|
||||
this.#assignments.push(pattern);
|
||||
this.visit(pattern.left);
|
||||
this.rightHandNodes.push(pattern.right);
|
||||
this.#assignments.pop();
|
||||
}
|
||||
CallExpression(node) {
|
||||
// arguments are right hand nodes.
|
||||
node.arguments.forEach(a => {
|
||||
this.rightHandNodes.push(a);
|
||||
});
|
||||
this.visit(node.callee);
|
||||
}
|
||||
Decorator() {
|
||||
// don't visit any decorators when exploring a pattern
|
||||
}
|
||||
Identifier(pattern) {
|
||||
const lastRestElement = this.#restElements.at(-1);
|
||||
this.#callback(pattern, {
|
||||
assignments: this.#assignments,
|
||||
rest: lastRestElement?.argument === pattern,
|
||||
topLevel: pattern === this.#rootPattern,
|
||||
});
|
||||
}
|
||||
MemberExpression(node) {
|
||||
// Computed property's key is a right hand node.
|
||||
if (node.computed) {
|
||||
this.rightHandNodes.push(node.property);
|
||||
}
|
||||
// the object is only read, write to its property.
|
||||
this.rightHandNodes.push(node.object);
|
||||
}
|
||||
Property(property) {
|
||||
// Computed property's key is a right hand node.
|
||||
if (property.computed) {
|
||||
this.rightHandNodes.push(property.key);
|
||||
}
|
||||
// If it's shorthand, its key is same as its value.
|
||||
// If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern).
|
||||
// If it's not shorthand, the name of new variable is its value's.
|
||||
this.visit(property.value);
|
||||
}
|
||||
RestElement(pattern) {
|
||||
this.#restElements.push(pattern);
|
||||
this.visit(pattern.argument);
|
||||
this.#restElements.pop();
|
||||
}
|
||||
SpreadElement(node) {
|
||||
this.visit(node.argument);
|
||||
}
|
||||
TSTypeAnnotation() {
|
||||
// we don't want to visit types
|
||||
}
|
||||
}
|
||||
exports.PatternVisitor = PatternVisitor;
|
||||
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = function (it) {
|
||||
const { configName, importerName } = it;
|
||||
|
||||
return `
|
||||
"${configName}" is invalid syntax for a config specifier.
|
||||
|
||||
* If your intention is to extend from a configuration exported from the plugin, add the configuration name after a slash: e.g. "${configName}/myConfig".
|
||||
* If this is the name of a shareable config instead of a plugin, remove the "plugin:" prefix: i.e. "${configName.slice("plugin:".length)}".
|
||||
|
||||
"${configName}" was referenced from the config file in "${importerName}".
|
||||
|
||||
If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting.
|
||||
`.trimStart();
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { v as vi, N as NodeBenchmarkRunner, S as Snapshots, T as TestRunner, a as assert, c as createExpect, g as globalExpect, i as inject, s as should, b as vitest } from './test.DNmyFkvJ.js';
|
||||
import { b as bench } from './benchmark.CX_oY03V.js';
|
||||
import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
|
||||
import { expectTypeOf } from 'expect-type';
|
||||
import { afterAll, afterEach, aroundAll, aroundEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
|
||||
import { chai } from '@vitest/expect';
|
||||
|
||||
const assertType = function assertType() {};
|
||||
|
||||
var index = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
BenchmarkRunner: NodeBenchmarkRunner,
|
||||
EvaluatedModules: VitestEvaluatedModules,
|
||||
Snapshots: Snapshots,
|
||||
TestRunner: TestRunner,
|
||||
afterAll: afterAll,
|
||||
afterEach: afterEach,
|
||||
aroundAll: aroundAll,
|
||||
aroundEach: aroundEach,
|
||||
assert: assert,
|
||||
assertType: assertType,
|
||||
beforeAll: beforeAll,
|
||||
beforeEach: beforeEach,
|
||||
bench: bench,
|
||||
chai: chai,
|
||||
createExpect: createExpect,
|
||||
describe: describe,
|
||||
expect: globalExpect,
|
||||
expectTypeOf: expectTypeOf,
|
||||
inject: inject,
|
||||
it: it,
|
||||
onTestFailed: onTestFailed,
|
||||
onTestFinished: onTestFinished,
|
||||
recordArtifact: recordArtifact,
|
||||
should: should,
|
||||
suite: suite,
|
||||
test: test,
|
||||
vi: vi,
|
||||
vitest: vitest
|
||||
});
|
||||
|
||||
export { assertType as a, index as i };
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,110 @@
|
||||
import * as util from "../core/util.js";
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "حروف", verb: "ہونا" },
|
||||
file: { unit: "بائٹس", verb: "ہونا" },
|
||||
array: { unit: "آئٹمز", verb: "ہونا" },
|
||||
set: { unit: "آئٹمز", verb: "ہونا" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "ان پٹ",
|
||||
email: "ای میل ایڈریس",
|
||||
url: "یو آر ایل",
|
||||
emoji: "ایموجی",
|
||||
uuid: "یو یو آئی ڈی",
|
||||
uuidv4: "یو یو آئی ڈی وی 4",
|
||||
uuidv6: "یو یو آئی ڈی وی 6",
|
||||
nanoid: "نینو آئی ڈی",
|
||||
guid: "جی یو آئی ڈی",
|
||||
cuid: "سی یو آئی ڈی",
|
||||
cuid2: "سی یو آئی ڈی 2",
|
||||
ulid: "یو ایل آئی ڈی",
|
||||
xid: "ایکس آئی ڈی",
|
||||
ksuid: "کے ایس یو آئی ڈی",
|
||||
datetime: "آئی ایس او ڈیٹ ٹائم",
|
||||
date: "آئی ایس او تاریخ",
|
||||
time: "آئی ایس او وقت",
|
||||
duration: "آئی ایس او مدت",
|
||||
ipv4: "آئی پی وی 4 ایڈریس",
|
||||
ipv6: "آئی پی وی 6 ایڈریس",
|
||||
cidrv4: "آئی پی وی 4 رینج",
|
||||
cidrv6: "آئی پی وی 6 رینج",
|
||||
base64: "بیس 64 ان کوڈڈ سٹرنگ",
|
||||
base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",
|
||||
json_string: "جے ایس او این سٹرنگ",
|
||||
e164: "ای 164 نمبر",
|
||||
jwt: "جے ڈبلیو ٹی",
|
||||
template_literal: "ان پٹ",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "نمبر",
|
||||
array: "آرے",
|
||||
null: "نل",
|
||||
};
|
||||
return (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type": {
|
||||
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
||||
const receivedType = util.parsedType(issue.input);
|
||||
const received = TypeDictionary[receivedType] ?? receivedType;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `غلط ان پٹ: instanceof ${issue.expected} متوقع تھا، ${received} موصول ہوا`;
|
||||
}
|
||||
return `غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `غلط ان پٹ: ${util.stringifyPrimitive(issue.values[0])} متوقع تھا`;
|
||||
return `غلط آپشن: ${util.joinValues(issue.values, "|")} میں سے ایک متوقع تھا`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`;
|
||||
return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;
|
||||
}
|
||||
return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with") {
|
||||
return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;
|
||||
}
|
||||
if (_issue.format === "ends_with")
|
||||
return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;
|
||||
if (_issue.format === "includes")
|
||||
return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;
|
||||
if (_issue.format === "regex")
|
||||
return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;
|
||||
return `غلط ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`;
|
||||
case "unrecognized_keys":
|
||||
return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${util.joinValues(issue.keys, "، ")}`;
|
||||
case "invalid_key":
|
||||
return `${issue.origin} میں غلط کی`;
|
||||
case "invalid_union":
|
||||
return "غلط ان پٹ";
|
||||
case "invalid_element":
|
||||
return `${issue.origin} میں غلط ویلیو`;
|
||||
default:
|
||||
return `غلط ان پٹ`;
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
[](https://travis-ci.org/digitaldesignlabs/es6-promisify)
|
||||
|
||||
# es6-promisify
|
||||
|
||||
Converts callback-based functions to Promise-based functions.
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://npmjs.org/package/es6-promisify)
|
||||
|
||||
```bash
|
||||
npm install --save es6-promisify
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
// Declare variables
|
||||
const promisify = require("es6-promisify");
|
||||
const fs = require("fs");
|
||||
|
||||
// Convert the stat function
|
||||
const stat = promisify(fs.stat);
|
||||
|
||||
// Now usable as a promise!
|
||||
stat("example.txt").then(function (stats) {
|
||||
console.log("Got stats", stats);
|
||||
}).catch(function (err) {
|
||||
console.error("Yikes!", err);
|
||||
});
|
||||
```
|
||||
|
||||
## Promisify methods
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
// Declare variables
|
||||
const promisify = require("es6-promisify");
|
||||
const redis = require("redis").createClient(6379, "localhost");
|
||||
|
||||
// Create a promise-based version of send_command
|
||||
const client = promisify(redis.send_command, redis);
|
||||
|
||||
// Send commands to redis and get a promise back
|
||||
client("ping").then(function (pong) {
|
||||
console.log("Got", pong);
|
||||
}).catch(function (err) {
|
||||
console.error("Unexpected error", err);
|
||||
}).then(function () {
|
||||
redis.quit();
|
||||
});
|
||||
```
|
||||
|
||||
## Handle callback multiple arguments
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
// Declare functions
|
||||
function test(cb) {
|
||||
return cb(undefined, 1, 2, 3);
|
||||
}
|
||||
|
||||
// Declare variables
|
||||
const promisify = require("es6-promisify");
|
||||
|
||||
// Create promise-based version of test
|
||||
const single = promisify(test);
|
||||
const multi = promisify(test, {multiArgs: true});
|
||||
|
||||
// Discards additional arguments
|
||||
single().then(function (result) {
|
||||
console.log(result); // 1
|
||||
});
|
||||
|
||||
// Returns all arguments as an array
|
||||
multi().then(function (result) {
|
||||
console.log(result); // [1, 2, 3]
|
||||
});
|
||||
```
|
||||
|
||||
### Tests
|
||||
Test with nodeunit
|
||||
```bash
|
||||
$ npm test
|
||||
```
|
||||
|
||||
Published under the [MIT License](http://opensource.org/licenses/MIT).
|
||||
@@ -0,0 +1,6 @@
|
||||
interface ExtractedSourceMap {
|
||||
map: any;
|
||||
}
|
||||
declare function extractSourcemapFromFile(code: string, filePath: string): ExtractedSourceMap | undefined;
|
||||
|
||||
export { extractSourcemapFromFile };
|
||||
@@ -0,0 +1,431 @@
|
||||
import {
|
||||
isFunction
|
||||
} from './utils';
|
||||
import {
|
||||
noop,
|
||||
nextId,
|
||||
PROMISE_ID,
|
||||
initializePromise
|
||||
} from './-internal';
|
||||
import {
|
||||
asap,
|
||||
setAsap,
|
||||
setScheduler
|
||||
} from './asap';
|
||||
|
||||
import all from './promise/all';
|
||||
import race from './promise/race';
|
||||
import Resolve from './promise/resolve';
|
||||
import Reject from './promise/reject';
|
||||
import then from './then';
|
||||
|
||||
function needsResolver() {
|
||||
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
|
||||
}
|
||||
|
||||
function needsNew() {
|
||||
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
|
||||
}
|
||||
|
||||
/**
|
||||
Promise objects represent the eventual result of an asynchronous operation. The
|
||||
primary way of interacting with a promise is through its `then` method, which
|
||||
registers callbacks to receive either a promise's eventual value or the reason
|
||||
why the promise cannot be fulfilled.
|
||||
|
||||
Terminology
|
||||
-----------
|
||||
|
||||
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
|
||||
- `thenable` is an object or function that defines a `then` method.
|
||||
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
|
||||
- `exception` is a value that is thrown using the throw statement.
|
||||
- `reason` is a value that indicates why a promise was rejected.
|
||||
- `settled` the final resting state of a promise, fulfilled or rejected.
|
||||
|
||||
A promise can be in one of three states: pending, fulfilled, or rejected.
|
||||
|
||||
Promises that are fulfilled have a fulfillment value and are in the fulfilled
|
||||
state. Promises that are rejected have a rejection reason and are in the
|
||||
rejected state. A fulfillment value is never a thenable.
|
||||
|
||||
Promises can also be said to *resolve* a value. If this value is also a
|
||||
promise, then the original promise's settled state will match the value's
|
||||
settled state. So a promise that *resolves* a promise that rejects will
|
||||
itself reject, and a promise that *resolves* a promise that fulfills will
|
||||
itself fulfill.
|
||||
|
||||
|
||||
Basic Usage:
|
||||
------------
|
||||
|
||||
```js
|
||||
let promise = new Promise(function(resolve, reject) {
|
||||
// on success
|
||||
resolve(value);
|
||||
|
||||
// on failure
|
||||
reject(reason);
|
||||
});
|
||||
|
||||
promise.then(function(value) {
|
||||
// on fulfillment
|
||||
}, function(reason) {
|
||||
// on rejection
|
||||
});
|
||||
```
|
||||
|
||||
Advanced Usage:
|
||||
---------------
|
||||
|
||||
Promises shine when abstracting away asynchronous interactions such as
|
||||
`XMLHttpRequest`s.
|
||||
|
||||
```js
|
||||
function getJSON(url) {
|
||||
return new Promise(function(resolve, reject){
|
||||
let xhr = new XMLHttpRequest();
|
||||
|
||||
xhr.open('GET', url);
|
||||
xhr.onreadystatechange = handler;
|
||||
xhr.responseType = 'json';
|
||||
xhr.setRequestHeader('Accept', 'application/json');
|
||||
xhr.send();
|
||||
|
||||
function handler() {
|
||||
if (this.readyState === this.DONE) {
|
||||
if (this.status === 200) {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
getJSON('/posts.json').then(function(json) {
|
||||
// on fulfillment
|
||||
}, function(reason) {
|
||||
// on rejection
|
||||
});
|
||||
```
|
||||
|
||||
Unlike callbacks, promises are great composable primitives.
|
||||
|
||||
```js
|
||||
Promise.all([
|
||||
getJSON('/posts'),
|
||||
getJSON('/comments')
|
||||
]).then(function(values){
|
||||
values[0] // => postsJSON
|
||||
values[1] // => commentsJSON
|
||||
|
||||
return values;
|
||||
});
|
||||
```
|
||||
|
||||
@class Promise
|
||||
@param {Function} resolver
|
||||
Useful for tooling.
|
||||
@constructor
|
||||
*/
|
||||
|
||||
class Promise {
|
||||
constructor(resolver) {
|
||||
this[PROMISE_ID] = nextId();
|
||||
this._result = this._state = undefined;
|
||||
this._subscribers = [];
|
||||
|
||||
if (noop !== resolver) {
|
||||
typeof resolver !== 'function' && needsResolver();
|
||||
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The primary way of interacting with a promise is through its `then` method,
|
||||
which registers callbacks to receive either a promise's eventual value or the
|
||||
reason why the promise cannot be fulfilled.
|
||||
|
||||
```js
|
||||
findUser().then(function(user){
|
||||
// user is available
|
||||
}, function(reason){
|
||||
// user is unavailable, and you are given the reason why
|
||||
});
|
||||
```
|
||||
|
||||
Chaining
|
||||
--------
|
||||
|
||||
The return value of `then` is itself a promise. This second, 'downstream'
|
||||
promise is resolved with the return value of the first promise's fulfillment
|
||||
or rejection handler, or rejected if the handler throws an exception.
|
||||
|
||||
```js
|
||||
findUser().then(function (user) {
|
||||
return user.name;
|
||||
}, function (reason) {
|
||||
return 'default name';
|
||||
}).then(function (userName) {
|
||||
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
|
||||
// will be `'default name'`
|
||||
});
|
||||
|
||||
findUser().then(function (user) {
|
||||
throw new Error('Found user, but still unhappy');
|
||||
}, function (reason) {
|
||||
throw new Error('`findUser` rejected and we're unhappy');
|
||||
}).then(function (value) {
|
||||
// never reached
|
||||
}, function (reason) {
|
||||
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
|
||||
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
|
||||
});
|
||||
```
|
||||
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
|
||||
|
||||
```js
|
||||
findUser().then(function (user) {
|
||||
throw new PedagogicalException('Upstream error');
|
||||
}).then(function (value) {
|
||||
// never reached
|
||||
}).then(function (value) {
|
||||
// never reached
|
||||
}, function (reason) {
|
||||
// The `PedgagocialException` is propagated all the way down to here
|
||||
});
|
||||
```
|
||||
|
||||
Assimilation
|
||||
------------
|
||||
|
||||
Sometimes the value you want to propagate to a downstream promise can only be
|
||||
retrieved asynchronously. This can be achieved by returning a promise in the
|
||||
fulfillment or rejection handler. The downstream promise will then be pending
|
||||
until the returned promise is settled. This is called *assimilation*.
|
||||
|
||||
```js
|
||||
findUser().then(function (user) {
|
||||
return findCommentsByAuthor(user);
|
||||
}).then(function (comments) {
|
||||
// The user's comments are now available
|
||||
});
|
||||
```
|
||||
|
||||
If the assimliated promise rejects, then the downstream promise will also reject.
|
||||
|
||||
```js
|
||||
findUser().then(function (user) {
|
||||
return findCommentsByAuthor(user);
|
||||
}).then(function (comments) {
|
||||
// If `findCommentsByAuthor` fulfills, we'll have the value here
|
||||
}, function (reason) {
|
||||
// If `findCommentsByAuthor` rejects, we'll have the reason here
|
||||
});
|
||||
```
|
||||
|
||||
Simple Example
|
||||
--------------
|
||||
|
||||
Synchronous Example
|
||||
|
||||
```javascript
|
||||
let result;
|
||||
|
||||
try {
|
||||
result = findResult();
|
||||
// success
|
||||
} catch(reason) {
|
||||
// failure
|
||||
}
|
||||
```
|
||||
|
||||
Errback Example
|
||||
|
||||
```js
|
||||
findResult(function(result, err){
|
||||
if (err) {
|
||||
// failure
|
||||
} else {
|
||||
// success
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Promise Example;
|
||||
|
||||
```javascript
|
||||
findResult().then(function(result){
|
||||
// success
|
||||
}, function(reason){
|
||||
// failure
|
||||
});
|
||||
```
|
||||
|
||||
Advanced Example
|
||||
--------------
|
||||
|
||||
Synchronous Example
|
||||
|
||||
```javascript
|
||||
let author, books;
|
||||
|
||||
try {
|
||||
author = findAuthor();
|
||||
books = findBooksByAuthor(author);
|
||||
// success
|
||||
} catch(reason) {
|
||||
// failure
|
||||
}
|
||||
```
|
||||
|
||||
Errback Example
|
||||
|
||||
```js
|
||||
|
||||
function foundBooks(books) {
|
||||
|
||||
}
|
||||
|
||||
function failure(reason) {
|
||||
|
||||
}
|
||||
|
||||
findAuthor(function(author, err){
|
||||
if (err) {
|
||||
failure(err);
|
||||
// failure
|
||||
} else {
|
||||
try {
|
||||
findBoooksByAuthor(author, function(books, err) {
|
||||
if (err) {
|
||||
failure(err);
|
||||
} else {
|
||||
try {
|
||||
foundBooks(books);
|
||||
} catch(reason) {
|
||||
failure(reason);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch(error) {
|
||||
failure(err);
|
||||
}
|
||||
// success
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Promise Example;
|
||||
|
||||
```javascript
|
||||
findAuthor().
|
||||
then(findBooksByAuthor).
|
||||
then(function(books){
|
||||
// found books
|
||||
}).catch(function(reason){
|
||||
// something went wrong
|
||||
});
|
||||
```
|
||||
|
||||
@method then
|
||||
@param {Function} onFulfilled
|
||||
@param {Function} onRejected
|
||||
Useful for tooling.
|
||||
@return {Promise}
|
||||
*/
|
||||
|
||||
/**
|
||||
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
|
||||
as the catch block of a try/catch statement.
|
||||
|
||||
```js
|
||||
function findAuthor(){
|
||||
throw new Error('couldn't find that author');
|
||||
}
|
||||
|
||||
// synchronous
|
||||
try {
|
||||
findAuthor();
|
||||
} catch(reason) {
|
||||
// something went wrong
|
||||
}
|
||||
|
||||
// async with promises
|
||||
findAuthor().catch(function(reason){
|
||||
// something went wrong
|
||||
});
|
||||
```
|
||||
|
||||
@method catch
|
||||
@param {Function} onRejection
|
||||
Useful for tooling.
|
||||
@return {Promise}
|
||||
*/
|
||||
catch(onRejection) {
|
||||
return this.then(null, onRejection);
|
||||
}
|
||||
|
||||
/**
|
||||
`finally` will be invoked regardless of the promise's fate just as native
|
||||
try/catch/finally behaves
|
||||
|
||||
Synchronous example:
|
||||
|
||||
```js
|
||||
findAuthor() {
|
||||
if (Math.random() > 0.5) {
|
||||
throw new Error();
|
||||
}
|
||||
return new Author();
|
||||
}
|
||||
|
||||
try {
|
||||
return findAuthor(); // succeed or fail
|
||||
} catch(error) {
|
||||
return findOtherAuther();
|
||||
} finally {
|
||||
// always runs
|
||||
// doesn't affect the return value
|
||||
}
|
||||
```
|
||||
|
||||
Asynchronous example:
|
||||
|
||||
```js
|
||||
findAuthor().catch(function(reason){
|
||||
return findOtherAuther();
|
||||
}).finally(function(){
|
||||
// author was either found, or not
|
||||
});
|
||||
```
|
||||
|
||||
@method finally
|
||||
@param {Function} callback
|
||||
@return {Promise}
|
||||
*/
|
||||
finally(callback) {
|
||||
let promise = this;
|
||||
let constructor = promise.constructor;
|
||||
|
||||
if ( isFunction(callback) ) {
|
||||
return promise.then(value => constructor.resolve(callback()).then(() => value),
|
||||
reason => constructor.resolve(callback()).then(() => { throw reason; }));
|
||||
}
|
||||
|
||||
return promise.then(callback, callback);
|
||||
}
|
||||
}
|
||||
|
||||
Promise.prototype.then = then;
|
||||
export default Promise;
|
||||
Promise.all = all;
|
||||
Promise.race = race;
|
||||
Promise.resolve = Resolve;
|
||||
Promise.reject = Reject;
|
||||
Promise._setScheduler = setScheduler;
|
||||
Promise._setAsap = setAsap;
|
||||
Promise._asap = asap;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
|
||||
Copyright (c) 2013 Arnout Kazemier and contributors
|
||||
Copyright (c) 2016 Luigi Pinca and contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"JSON.stringify@native": {
|
||||
"name": "JSON.stringify@native",
|
||||
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "libs",
|
||||
"hz": 14399.576564897297,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.025493726819537762,
|
||||
"rhz": 2.334401010263042,
|
||||
"sampleSize": 171
|
||||
},
|
||||
"fast-stable-stringify@a9f81e8": {
|
||||
"name": "fast-stable-stringify@a9f81e8",
|
||||
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "libs",
|
||||
"hz": 6168.424577264358,
|
||||
"success": true,
|
||||
"fastest": true,
|
||||
"rme": 0.016452779720660355,
|
||||
"rhz": 1,
|
||||
"sampleSize": 151
|
||||
},
|
||||
"json-stable-stringify@1.0.1": {
|
||||
"name": "json-stable-stringify@1.0.1",
|
||||
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "libs",
|
||||
"hz": 3365.990566485956,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.02423016956488021,
|
||||
"rhz": 0.5456807527309904,
|
||||
"sampleSize": 172
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
function _readOnlyError(r) {
|
||||
throw new TypeError('"' + r + '" is read-only');
|
||||
}
|
||||
export { _readOnlyError as default };
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_md.d.ts","sourceRoot":"","sources":["../src/_md.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,KAAK,EAAE,IAAI,EAAwD,MAAM,YAAY,CAAC;AAEpG,gGAAgG;AAChG,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,OAAO,GACZ,IAAI,CAUN;AAED,wBAAwB;AACxB,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,yDAAyD;AACzD,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;GAGG;AACH,8BAAsB,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IAC/D,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAC/D,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI;IAErC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAGvB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAEhB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO;IASjF,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IA0BzB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI;IAkCjC,MAAM,IAAI,UAAU;IAOpB,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAWrB,KAAK,IAAI,CAAC;CAGX;AAED;;;GAGG;AAEH,4EAA4E;AAC5E,eAAO,MAAM,SAAS,EAAE,WAEtB,CAAC;AAEH,8EAA8E;AAC9E,eAAO,MAAM,SAAS,EAAE,WAEtB,CAAC;AAEH,6EAA6E;AAC7E,eAAO,MAAM,SAAS,EAAE,WAGtB,CAAC;AAEH,4EAA4E;AAC5E,eAAO,MAAM,SAAS,EAAE,WAGtB,CAAC"}
|
||||
@@ -0,0 +1,22 @@
|
||||
function _regeneratorDefine(e, r, n, t) {
|
||||
var i = Object.defineProperty;
|
||||
try {
|
||||
i({}, "", {});
|
||||
} catch (e) {
|
||||
i = 0;
|
||||
}
|
||||
_regeneratorDefine = function regeneratorDefine(e, r, n, t) {
|
||||
function o(r, n) {
|
||||
_regeneratorDefine(e, r, function (e) {
|
||||
return this._invoke(r, n, e);
|
||||
});
|
||||
}
|
||||
r ? i ? i(e, r, {
|
||||
value: n,
|
||||
enumerable: !t,
|
||||
configurable: !t,
|
||||
writable: !t
|
||||
}) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
|
||||
}, _regeneratorDefine(e, r, n, t);
|
||||
}
|
||||
export { _regeneratorDefine as default };
|
||||
@@ -0,0 +1,30 @@
|
||||
/*! *****************************************************************************
|
||||
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,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
/**
|
||||
* Represents the completion of an asynchronous operation
|
||||
*/
|
||||
interface Promise<T> {
|
||||
/**
|
||||
* Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
|
||||
* resolved value cannot be modified from the callback.
|
||||
* @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
|
||||
* @returns A Promise for the completion of the callback.
|
||||
*/
|
||||
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-Zhafd14U.mjs";
|
||||
import { f as __decorate, h as PlainObjectLike, m as lazyProp, u as transformToRollupOutput } from "./bindingify-input-options-C-Zsy1EG.mjs";
|
||||
import { l as PluginDriver, s as validateOption, t as createBundlerOptions } from "./create-bundler-option-wRiQzEJ3.mjs";
|
||||
import { i as unwrapBindingResult } from "./error-CVc7IgvG.mjs";
|
||||
//#region src/types/rolldown-output-impl.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
var RolldownOutputImpl = class extends PlainObjectLike {
|
||||
bindingOutputs;
|
||||
constructor(bindingOutputs) {
|
||||
super();
|
||||
this.bindingOutputs = bindingOutputs;
|
||||
}
|
||||
get output() {
|
||||
return transformToRollupOutput(this.bindingOutputs).output;
|
||||
}
|
||||
__rolldown_external_memory_handle__(keepDataAlive) {
|
||||
const results = this.output.map((item) => item.__rolldown_external_memory_handle__(keepDataAlive));
|
||||
if (!results.every((r) => r.freed)) {
|
||||
const reasons = results.filter((r) => !r.freed).map((r) => r.reason).filter(Boolean);
|
||||
return {
|
||||
freed: false,
|
||||
reason: `Failed to free ${reasons.length} item(s): ${reasons.join("; ")}`
|
||||
};
|
||||
}
|
||||
return { freed: true };
|
||||
}
|
||||
};
|
||||
__decorate([lazyProp], RolldownOutputImpl.prototype, "output", null);
|
||||
//#endregion
|
||||
//#region src/api/rolldown/rolldown-build.ts
|
||||
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
|
||||
/**
|
||||
* The bundle object returned by {@linkcode rolldown} function.
|
||||
*
|
||||
* @category Programmatic APIs
|
||||
*/
|
||||
var RolldownBuild = class {
|
||||
#inputOptions;
|
||||
#bundler;
|
||||
#stopWorkers;
|
||||
#asyncRuntimeReleased = false;
|
||||
/** @hidden should not be used directly */
|
||||
constructor(inputOptions) {
|
||||
this.#inputOptions = inputOptions;
|
||||
this.#bundler = new import_binding.BindingBundler();
|
||||
(0, import_binding.startAsyncRuntime)();
|
||||
}
|
||||
/**
|
||||
* Whether the bundle has been closed.
|
||||
*
|
||||
* If the bundle is closed, calling other methods will throw an error.
|
||||
*/
|
||||
get closed() {
|
||||
return this.#bundler.closed;
|
||||
}
|
||||
/**
|
||||
* Generate bundles in-memory.
|
||||
*
|
||||
* If you directly want to write bundles to disk, use the {@linkcode write} method instead.
|
||||
*
|
||||
* @param outputOptions The output options.
|
||||
* @returns The generated bundle.
|
||||
* @throws {@linkcode BundleError} When an error occurs during the build.
|
||||
*/
|
||||
async generate(outputOptions = {}) {
|
||||
return this.#build(false, outputOptions);
|
||||
}
|
||||
/**
|
||||
* Generate and write bundles to disk.
|
||||
*
|
||||
* If you want to generate bundles in-memory, use the {@linkcode generate} method instead.
|
||||
*
|
||||
* @param outputOptions The output options.
|
||||
* @returns The generated bundle.
|
||||
* @throws {@linkcode BundleError} When an error occurs during the build.
|
||||
*/
|
||||
async write(outputOptions = {}) {
|
||||
return this.#build(true, outputOptions);
|
||||
}
|
||||
/**
|
||||
* Close the bundle and free resources.
|
||||
*
|
||||
* This method should be called even if the {@linkcode generate} method
|
||||
* or the {@linkcode write} method threw an error. It should be called
|
||||
* even if neither of the methods are called.
|
||||
*
|
||||
* This method is called automatically when using `using` syntax.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { rolldown } from 'rolldown';
|
||||
*
|
||||
* {
|
||||
* using bundle = await rolldown({ input: 'src/main.js' });
|
||||
* const output = await bundle.generate({ format: 'esm' });
|
||||
* console.log(output);
|
||||
* // bundle.close() is called automatically here
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
async close() {
|
||||
const shouldRelease = !this.#asyncRuntimeReleased;
|
||||
this.#asyncRuntimeReleased = true;
|
||||
try {
|
||||
await this.#stopWorkers?.();
|
||||
await this.#bundler.close();
|
||||
this.#stopWorkers = void 0;
|
||||
} finally {
|
||||
if (shouldRelease) (0, import_binding.shutdownAsyncRuntime)();
|
||||
}
|
||||
}
|
||||
/** @hidden documented in close method */
|
||||
async [Symbol.asyncDispose]() {
|
||||
await this.close();
|
||||
}
|
||||
/**
|
||||
* @experimental
|
||||
* @hidden not ready for public usage yet
|
||||
*/
|
||||
get watchFiles() {
|
||||
return Promise.resolve(this.#bundler.getWatchFiles());
|
||||
}
|
||||
async #build(isWrite, outputOptions) {
|
||||
validateOption("output", outputOptions);
|
||||
await this.#stopWorkers?.();
|
||||
const option = await createBundlerOptions(this.#inputOptions, outputOptions, false, true);
|
||||
try {
|
||||
this.#stopWorkers = option.stopWorkers;
|
||||
let output;
|
||||
if (isWrite) output = await this.#bundler.write(option.bundlerOptions);
|
||||
else output = await this.#bundler.generate(option.bundlerOptions);
|
||||
return new RolldownOutputImpl(unwrapBindingResult(output));
|
||||
} catch (e) {
|
||||
await option.stopWorkers?.();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
//#region src/api/rolldown/index.ts
|
||||
/**
|
||||
* The API compatible with Rollup's `rollup` function.
|
||||
*
|
||||
* Unlike Rollup, the module graph is not built until the methods of the bundle object are called.
|
||||
*
|
||||
* @param input The input options object.
|
||||
* @returns A Promise that resolves to a bundle object.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { rolldown } from 'rolldown';
|
||||
*
|
||||
* let bundle, failed = false;
|
||||
* try {
|
||||
* bundle = await rolldown({
|
||||
* input: 'src/main.js',
|
||||
* });
|
||||
* await bundle.write({
|
||||
* format: 'esm',
|
||||
* });
|
||||
* } catch (e) {
|
||||
* console.error(e);
|
||||
* failed = true;
|
||||
* }
|
||||
* if (bundle) {
|
||||
* await bundle.close();
|
||||
* }
|
||||
* process.exitCode = failed ? 1 : 0;
|
||||
* ```
|
||||
*
|
||||
* @category Programmatic APIs
|
||||
*/
|
||||
const rolldown = async (input) => {
|
||||
validateOption("input", input);
|
||||
return new RolldownBuild(await PluginDriver.callOptionsHook(input));
|
||||
};
|
||||
//#endregion
|
||||
export { rolldown as t };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
|
||||
// npx nx generate-lib repo
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.esnext_intl = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const esnext_temporal_1 = require("./esnext.temporal");
|
||||
exports.esnext_intl = {
|
||||
libs: [esnext_temporal_1.esnext_temporal],
|
||||
variables: [['Intl', base_config_1.TYPE_VALUE]],
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict'
|
||||
|
||||
const fs = require('node:fs')
|
||||
const { once } = require('node:events')
|
||||
const { Transform } = require('node:stream')
|
||||
|
||||
async function run (opts) {
|
||||
if (!opts.destination) throw new Error('kaboom')
|
||||
const stream = fs.createWriteStream(opts.destination)
|
||||
await once(stream, 'open')
|
||||
const t = new Transform({
|
||||
transform (chunk, enc, cb) {
|
||||
setImmediate(cb, null, chunk.toString().toUpperCase())
|
||||
}
|
||||
})
|
||||
t.pipe(stream)
|
||||
return t
|
||||
}
|
||||
|
||||
module.exports = run
|
||||
@@ -0,0 +1,10 @@
|
||||
# `@typescript-eslint/visitor-keys`
|
||||
|
||||
> Visitor keys used to help traverse the TypeScript-ESTree AST.
|
||||
|
||||
## ✋ Internal Package
|
||||
|
||||
This is an _internal package_ to the [typescript-eslint monorepo](https://github.com/typescript-eslint/typescript-eslint).
|
||||
You likely don't want to use it directly.
|
||||
|
||||
👉 See **https://typescript-eslint.io** for docs on typescript-eslint.
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"wtf8.d.ts","sourceRoot":"","sources":["../../../src/api/node/wtf8.ts"],"names":[],"mappings":"AAOA,KAAK,aAAa,GAAG,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AA6B1D,qBAAa,WAAY,SAAQ,WAAW;IAC/B,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,uBAAuB,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM;CAkC3F"}
|
||||
@@ -0,0 +1,939 @@
|
||||
import { expect, expectTypeOf, test } from "vitest";
|
||||
import * as z from "zod/v4";
|
||||
import type { util } from "zod/v4/core";
|
||||
|
||||
test("z.boolean", () => {
|
||||
const a = z.boolean();
|
||||
expect(z.parse(a, true)).toEqual(true);
|
||||
expect(z.parse(a, false)).toEqual(false);
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
expect(() => z.parse(a, "true")).toThrow();
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<boolean>();
|
||||
});
|
||||
|
||||
test("z.bigint", () => {
|
||||
const a = z.bigint();
|
||||
expect(z.parse(a, BigInt(123))).toEqual(BigInt(123));
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
expect(() => z.parse(a, "123")).toThrow();
|
||||
});
|
||||
|
||||
test("z.symbol", () => {
|
||||
const a = z.symbol();
|
||||
const sym = Symbol();
|
||||
expect(z.parse(a, sym)).toEqual(sym);
|
||||
expect(() => z.parse(a, "symbol")).toThrow();
|
||||
});
|
||||
|
||||
test("z.date", () => {
|
||||
const a = z.date();
|
||||
const date = new Date();
|
||||
expect(z.parse(a, date)).toEqual(date);
|
||||
expect(() => z.parse(a, "date")).toThrow();
|
||||
});
|
||||
|
||||
test("z.coerce.string", () => {
|
||||
const a = z.coerce.string();
|
||||
expect(z.parse(a, 123)).toEqual("123");
|
||||
expect(z.parse(a, true)).toEqual("true");
|
||||
expect(z.parse(a, null)).toEqual("null");
|
||||
expect(z.parse(a, undefined)).toEqual("undefined");
|
||||
});
|
||||
|
||||
test("z.coerce.number", () => {
|
||||
const a = z.coerce.number();
|
||||
expect(z.parse(a, "123")).toEqual(123);
|
||||
expect(z.parse(a, "123.45")).toEqual(123.45);
|
||||
expect(z.parse(a, true)).toEqual(1);
|
||||
expect(z.parse(a, false)).toEqual(0);
|
||||
expect(() => z.parse(a, "abc")).toThrow();
|
||||
});
|
||||
|
||||
test("z.coerce.boolean", () => {
|
||||
const a = z.coerce.boolean();
|
||||
// test booleans
|
||||
expect(z.parse(a, true)).toEqual(true);
|
||||
expect(z.parse(a, false)).toEqual(false);
|
||||
expect(z.parse(a, "true")).toEqual(true);
|
||||
expect(z.parse(a, "false")).toEqual(true);
|
||||
expect(z.parse(a, 1)).toEqual(true);
|
||||
expect(z.parse(a, 0)).toEqual(false);
|
||||
expect(z.parse(a, {})).toEqual(true);
|
||||
expect(z.parse(a, [])).toEqual(true);
|
||||
expect(z.parse(a, undefined)).toEqual(false);
|
||||
expect(z.parse(a, null)).toEqual(false);
|
||||
expect(z.parse(a, "")).toEqual(false);
|
||||
});
|
||||
|
||||
test("z.coerce.bigint", () => {
|
||||
const a = z.coerce.bigint();
|
||||
expect(z.parse(a, "123")).toEqual(BigInt(123));
|
||||
expect(z.parse(a, 123)).toEqual(BigInt(123));
|
||||
expect(() => z.parse(a, "abc")).toThrow();
|
||||
});
|
||||
|
||||
test("z.coerce.date", () => {
|
||||
const a = z.coerce.date();
|
||||
const date = new Date();
|
||||
expect(z.parse(a, date.toISOString())).toEqual(date);
|
||||
expect(z.parse(a, date.getTime())).toEqual(date);
|
||||
expect(() => z.parse(a, "invalid date")).toThrow();
|
||||
});
|
||||
|
||||
test("z.iso.datetime", () => {
|
||||
const d1 = "2021-01-01T00:00:00Z";
|
||||
const d2 = "2021-01-01T00:00:00.123Z";
|
||||
const d3 = "2021-01-01T00:00:00";
|
||||
const d4 = "2021-01-01T00:00:00+07:00";
|
||||
const d5 = "bad data";
|
||||
|
||||
// local: false, offset: false, precision: null
|
||||
const a = z.iso.datetime();
|
||||
expect(z.safeParse(a, d1).success).toEqual(true);
|
||||
expect(z.safeParse(a, d2).success).toEqual(true);
|
||||
expect(z.safeParse(a, d3).success).toEqual(false);
|
||||
expect(z.safeParse(a, d4).success).toEqual(false);
|
||||
expect(z.safeParse(a, d5).success).toEqual(false);
|
||||
|
||||
const b = z.iso.datetime({ local: true });
|
||||
expect(z.safeParse(b, d1).success).toEqual(true);
|
||||
expect(z.safeParse(b, d2).success).toEqual(true);
|
||||
expect(z.safeParse(b, d3).success).toEqual(true);
|
||||
expect(z.safeParse(b, d4).success).toEqual(false);
|
||||
expect(z.safeParse(b, d5).success).toEqual(false);
|
||||
|
||||
const c = z.iso.datetime({ offset: true });
|
||||
expect(z.safeParse(c, d1).success).toEqual(true);
|
||||
expect(z.safeParse(c, d2).success).toEqual(true);
|
||||
expect(z.safeParse(c, d3).success).toEqual(false);
|
||||
expect(z.safeParse(c, d4).success).toEqual(true);
|
||||
expect(z.safeParse(c, d5).success).toEqual(false);
|
||||
|
||||
const d = z.iso.datetime({ precision: 3 });
|
||||
expect(z.safeParse(d, d1).success).toEqual(false);
|
||||
expect(z.safeParse(d, d2).success).toEqual(true);
|
||||
expect(z.safeParse(d, d3).success).toEqual(false);
|
||||
expect(z.safeParse(d, d4).success).toEqual(false);
|
||||
expect(z.safeParse(d, d5).success).toEqual(false);
|
||||
});
|
||||
|
||||
test("z.iso.date", () => {
|
||||
const d1 = "2021-01-01";
|
||||
const d2 = "bad data";
|
||||
|
||||
const a = z.iso.date();
|
||||
expect(z.safeParse(a, d1).success).toEqual(true);
|
||||
expect(z.safeParse(a, d2).success).toEqual(false);
|
||||
|
||||
const b = z.string().check(z.iso.date());
|
||||
expect(z.safeParse(b, d1).success).toEqual(true);
|
||||
expect(z.safeParse(b, d2).success).toEqual(false);
|
||||
});
|
||||
|
||||
test("z.iso.time", () => {
|
||||
const d1 = "00:00:00";
|
||||
const d2 = "00:00:00.123";
|
||||
const d3 = "bad data";
|
||||
|
||||
const a = z.iso.time();
|
||||
expect(z.safeParse(a, d1).success).toEqual(true);
|
||||
expect(z.safeParse(a, d2).success).toEqual(true);
|
||||
expect(z.safeParse(a, d3).success).toEqual(false);
|
||||
|
||||
const b = z.iso.time({ precision: 3 });
|
||||
expect(z.safeParse(b, d1).success).toEqual(false);
|
||||
expect(z.safeParse(b, d2).success).toEqual(true);
|
||||
expect(z.safeParse(b, d3).success).toEqual(false);
|
||||
|
||||
const c = z.string().check(z.iso.time());
|
||||
expect(z.safeParse(c, d1).success).toEqual(true);
|
||||
expect(z.safeParse(c, d2).success).toEqual(true);
|
||||
expect(z.safeParse(c, d3).success).toEqual(false);
|
||||
});
|
||||
|
||||
test("z.iso.duration", () => {
|
||||
const d1 = "P3Y6M4DT12H30M5S";
|
||||
const d2 = "bad data";
|
||||
|
||||
const a = z.iso.duration();
|
||||
expect(z.safeParse(a, d1).success).toEqual(true);
|
||||
expect(z.safeParse(a, d2).success).toEqual(false);
|
||||
|
||||
const b = z.string().check(z.iso.duration());
|
||||
expect(z.safeParse(b, d1).success).toEqual(true);
|
||||
expect(z.safeParse(b, d2).success).toEqual(false);
|
||||
});
|
||||
|
||||
test("z.undefined", () => {
|
||||
const a = z.undefined();
|
||||
expect(z.parse(a, undefined)).toEqual(undefined);
|
||||
expect(() => z.parse(a, "undefined")).toThrow();
|
||||
});
|
||||
|
||||
test("z.null", () => {
|
||||
const a = z.null();
|
||||
expect(z.parse(a, null)).toEqual(null);
|
||||
expect(() => z.parse(a, "null")).toThrow();
|
||||
});
|
||||
|
||||
test("z.any", () => {
|
||||
const a = z.any();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, 123)).toEqual(123);
|
||||
expect(z.parse(a, true)).toEqual(true);
|
||||
expect(z.parse(a, null)).toEqual(null);
|
||||
expect(z.parse(a, undefined)).toEqual(undefined);
|
||||
z.parse(a, {});
|
||||
z.parse(a, []);
|
||||
z.parse(a, Symbol());
|
||||
z.parse(a, new Date());
|
||||
});
|
||||
|
||||
test("z.unknown", () => {
|
||||
const a = z.unknown();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, 123)).toEqual(123);
|
||||
expect(z.parse(a, true)).toEqual(true);
|
||||
expect(z.parse(a, null)).toEqual(null);
|
||||
expect(z.parse(a, undefined)).toEqual(undefined);
|
||||
z.parse(a, {});
|
||||
z.parse(a, []);
|
||||
z.parse(a, Symbol());
|
||||
z.parse(a, new Date());
|
||||
});
|
||||
|
||||
test("z.never", () => {
|
||||
const a = z.never();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
});
|
||||
|
||||
test("z.void", () => {
|
||||
const a = z.void();
|
||||
expect(z.parse(a, undefined)).toEqual(undefined);
|
||||
expect(() => z.parse(a, null)).toThrow();
|
||||
});
|
||||
|
||||
test("z.array", () => {
|
||||
const a = z.array(z.string());
|
||||
expect(z.parse(a, ["hello", "world"])).toEqual(["hello", "world"]);
|
||||
expect(() => z.parse(a, [123])).toThrow();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
});
|
||||
|
||||
test("z.union", () => {
|
||||
const a = z.union([z.string(), z.number()]);
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, 123)).toEqual(123);
|
||||
expect(() => z.parse(a, true)).toThrow();
|
||||
});
|
||||
|
||||
test("z.intersection", () => {
|
||||
const a = z.intersection(z.object({ a: z.string() }), z.object({ b: z.number() }));
|
||||
expect(z.parse(a, { a: "hello", b: 123 })).toEqual({ a: "hello", b: 123 });
|
||||
expect(() => z.parse(a, { a: "hello" })).toThrow();
|
||||
expect(() => z.parse(a, { b: 123 })).toThrow();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
});
|
||||
|
||||
test("z.tuple", () => {
|
||||
const a = z.tuple([z.string(), z.number()]);
|
||||
expect(z.parse(a, ["hello", 123])).toEqual(["hello", 123]);
|
||||
expect(() => z.parse(a, ["hello", "world"])).toThrow();
|
||||
expect(() => z.parse(a, [123, 456])).toThrow();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
|
||||
// tuple with rest
|
||||
const b = z.tuple([z.string(), z.number(), z.optional(z.string())], z.boolean());
|
||||
type b = z.output<typeof b>;
|
||||
|
||||
expectTypeOf<b>().toEqualTypeOf<[string, number, (string | undefined)?, ...boolean[]]>();
|
||||
const datas = [
|
||||
["hello", 123],
|
||||
["hello", 123, "world"],
|
||||
["hello", 123, "world", true],
|
||||
["hello", 123, "world", true, false, true],
|
||||
];
|
||||
for (const data of datas) {
|
||||
expect(z.parse(b, data)).toEqual(data);
|
||||
}
|
||||
|
||||
expect(() => z.parse(b, ["hello", 123, 123])).toThrow();
|
||||
expect(() => z.parse(b, ["hello", 123, "world", 123])).toThrow();
|
||||
|
||||
// tuple with readonly args
|
||||
const cArgs = [z.string(), z.number(), z.optional(z.string())] as const;
|
||||
const c = z.tuple(cArgs, z.boolean());
|
||||
type c = z.output<typeof c>;
|
||||
expectTypeOf<c>().toEqualTypeOf<[string, number, (string | undefined)?, ...boolean[]]>();
|
||||
// type c = z.output<typeof c>;
|
||||
});
|
||||
|
||||
test("z.record", () => {
|
||||
// record schema with enum keys
|
||||
const a = z.record(z.string(), z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<Record<string, string>>();
|
||||
|
||||
const b = z.record(z.union([z.string(), z.number(), z.symbol()]), z.string());
|
||||
type b = z.output<typeof b>;
|
||||
expectTypeOf<b>().toEqualTypeOf<Record<string | number | symbol, string>>();
|
||||
expect(z.parse(b, { a: "hello", 1: "world", [Symbol.for("asdf")]: "symbol" })).toEqual({
|
||||
a: "hello",
|
||||
1: "world",
|
||||
[Symbol.for("asdf")]: "symbol",
|
||||
});
|
||||
|
||||
// enum keys
|
||||
const c = z.record(z.enum(["a", "b", "c"]), z.string());
|
||||
type c = z.output<typeof c>;
|
||||
expectTypeOf<c>().toEqualTypeOf<Record<"a" | "b" | "c", string>>();
|
||||
expect(z.parse(c, { a: "hello", b: "world", c: "world" })).toEqual({
|
||||
a: "hello",
|
||||
b: "world",
|
||||
c: "world",
|
||||
});
|
||||
// missing keys
|
||||
expect(() => z.parse(c, { a: "hello", b: "world" })).toThrow();
|
||||
// extra keys
|
||||
expect(() => z.parse(c, { a: "hello", b: "world", c: "world", d: "world" })).toThrow();
|
||||
|
||||
// partial enum
|
||||
const d = z.record(z.enum(["a", "b"]).or(z.never()), z.string());
|
||||
type d = z.output<typeof d>;
|
||||
expectTypeOf<d>().toEqualTypeOf<Record<"a" | "b", string>>();
|
||||
|
||||
// literal union keys
|
||||
const e = z.record(z.union([z.literal("a"), z.literal(0)]), z.string());
|
||||
type e = z.output<typeof e>;
|
||||
expectTypeOf<e>().toEqualTypeOf<Record<"a" | 0, string>>();
|
||||
expect(z.parse(e, { a: "hello", 0: "world" })).toEqual({
|
||||
a: "hello",
|
||||
0: "world",
|
||||
});
|
||||
|
||||
// TypeScript enum keys
|
||||
enum Enum {
|
||||
A = 0,
|
||||
B = "hi",
|
||||
}
|
||||
|
||||
const f = z.record(z.enum(Enum), z.string());
|
||||
type f = z.output<typeof f>;
|
||||
expectTypeOf<f>().toEqualTypeOf<Record<Enum, string>>();
|
||||
expect(z.parse(f, { [Enum.A]: "hello", [Enum.B]: "world" })).toEqual({
|
||||
[Enum.A]: "hello",
|
||||
[Enum.B]: "world",
|
||||
});
|
||||
});
|
||||
|
||||
test("z.map", () => {
|
||||
const a = z.map(z.string(), z.number());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<Map<string, number>>();
|
||||
expect(z.parse(a, new Map([["hello", 123]]))).toEqual(new Map([["hello", 123]]));
|
||||
expect(() => z.parse(a, new Map([["hello", "world"]]))).toThrow();
|
||||
expect(() => z.parse(a, new Map([[1243, "world"]]))).toThrow();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
|
||||
const r1 = z.safeParse(a, new Map([[123, 123]]));
|
||||
expect(r1.error?.issues[0].code).toEqual("invalid_type");
|
||||
expect(r1.error?.issues[0].path).toEqual([123]);
|
||||
|
||||
const r2: any = z.safeParse(a, new Map([[BigInt(123), 123]]));
|
||||
expect(r2.error!.issues[0].code).toEqual("invalid_key");
|
||||
expect(r2.error!.issues[0].path).toEqual([]);
|
||||
|
||||
const r3: any = z.safeParse(a, new Map([["hello", "world"]]));
|
||||
expect(r3.error!.issues[0].code).toEqual("invalid_type");
|
||||
expect(r3.error!.issues[0].path).toEqual(["hello"]);
|
||||
});
|
||||
|
||||
test("z.map invalid_element", () => {
|
||||
const a = z.map(z.bigint(), z.number());
|
||||
const r1 = z.safeParse(a, new Map([[BigInt(123), BigInt(123)]]));
|
||||
|
||||
expect(r1.error!.issues[0].code).toEqual("invalid_element");
|
||||
expect(r1.error!.issues[0].path).toEqual([]);
|
||||
});
|
||||
|
||||
test("z.map async", async () => {
|
||||
const a = z.map(z.string().check(z.refine(async () => true)), z.number().check(z.refine(async () => true)));
|
||||
const d1 = new Map([["hello", 123]]);
|
||||
expect(await z.parseAsync(a, d1)).toEqual(d1);
|
||||
|
||||
await expect(z.parseAsync(a, new Map([[123, 123]]))).rejects.toThrow();
|
||||
await expect(z.parseAsync(a, new Map([["hi", "world"]]))).rejects.toThrow();
|
||||
await expect(z.parseAsync(a, new Map([[1243, "world"]]))).rejects.toThrow();
|
||||
await expect(z.parseAsync(a, "hello")).rejects.toThrow();
|
||||
|
||||
const r = await z.safeParseAsync(a, new Map([[123, 123]]));
|
||||
expect(r.success).toEqual(false);
|
||||
expect(r.error!.issues[0].code).toEqual("invalid_type");
|
||||
expect(r.error!.issues[0].path).toEqual([123]);
|
||||
});
|
||||
|
||||
test("z.set", () => {
|
||||
const a = z.set(z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<Set<string>>();
|
||||
expect(z.parse(a, new Set(["hello", "world"]))).toEqual(new Set(["hello", "world"]));
|
||||
expect(() => z.parse(a, new Set([123]))).toThrow();
|
||||
expect(() => z.parse(a, ["hello", "world"])).toThrow();
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
|
||||
const b = z.set(z.number());
|
||||
expect(z.parse(b, new Set([1, 2, 3]))).toEqual(new Set([1, 2, 3]));
|
||||
expect(() => z.parse(b, new Set(["hello"]))).toThrow();
|
||||
expect(() => z.parse(b, [1, 2, 3])).toThrow();
|
||||
expect(() => z.parse(b, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.enum", () => {
|
||||
const a = z.enum(["A", "B", "C"]);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<"A" | "B" | "C">();
|
||||
expect(z.parse(a, "A")).toEqual("A");
|
||||
expect(z.parse(a, "B")).toEqual("B");
|
||||
expect(z.parse(a, "C")).toEqual("C");
|
||||
expect(() => z.parse(a, "D")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
|
||||
expect(a.enum.A).toEqual("A");
|
||||
expect(a.enum.B).toEqual("B");
|
||||
expect(a.enum.C).toEqual("C");
|
||||
expect((a.enum as any).D).toEqual(undefined);
|
||||
});
|
||||
|
||||
test("z.enum - native", () => {
|
||||
enum NativeEnum {
|
||||
A = "A",
|
||||
B = "B",
|
||||
C = "C",
|
||||
}
|
||||
const a = z.enum(NativeEnum);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
|
||||
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
|
||||
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
|
||||
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
|
||||
expect(() => z.parse(a, "D")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
|
||||
// test a.enum
|
||||
a;
|
||||
expect(a.enum.A).toEqual(NativeEnum.A);
|
||||
expect(a.enum.B).toEqual(NativeEnum.B);
|
||||
expect(a.enum.C).toEqual(NativeEnum.C);
|
||||
});
|
||||
|
||||
test("z.nativeEnum", () => {
|
||||
enum NativeEnum {
|
||||
A = "A",
|
||||
B = "B",
|
||||
C = "C",
|
||||
}
|
||||
const a = z.nativeEnum(NativeEnum);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
|
||||
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
|
||||
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
|
||||
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
|
||||
expect(() => z.parse(a, "D")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
|
||||
// test a.enum
|
||||
a;
|
||||
expect(a.enum.A).toEqual(NativeEnum.A);
|
||||
expect(a.enum.B).toEqual(NativeEnum.B);
|
||||
expect(a.enum.C).toEqual(NativeEnum.C);
|
||||
});
|
||||
|
||||
test("z.literal", () => {
|
||||
const a = z.literal("hello");
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<"hello">();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(a, "world")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.file", () => {
|
||||
const a = z.file();
|
||||
const file = new File(["content"], "filename.txt", { type: "text/plain" });
|
||||
expect(z.parse(a, file)).toEqual(file);
|
||||
expect(() => z.parse(a, "file")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.transform", () => {
|
||||
const a = z.pipe(
|
||||
z.string(),
|
||||
z.transform((val) => val.toUpperCase())
|
||||
);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, "hello")).toEqual("HELLO");
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.transform async", async () => {
|
||||
const a = z.pipe(
|
||||
z.string(),
|
||||
z.transform(async (val) => val.toUpperCase())
|
||||
);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(await z.parseAsync(a, "hello")).toEqual("HELLO");
|
||||
await expect(() => z.parseAsync(a, 123)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("z.preprocess", () => {
|
||||
const a = z.pipe(
|
||||
z.transform((val) => String(val).toUpperCase()),
|
||||
z.string()
|
||||
);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, 123)).toEqual("123");
|
||||
expect(z.parse(a, true)).toEqual("TRUE");
|
||||
expect(z.parse(a, BigInt(1234))).toEqual("1234");
|
||||
// expect(() => z.parse(a, Symbol("asdf"))).toThrow();
|
||||
});
|
||||
|
||||
// test("z.preprocess async", () => {
|
||||
// const a = z.preprocess(async (val) => String(val), z.string());
|
||||
// type a = z.output<typeof a>;
|
||||
// expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
// expect(z.parse(a, 123)).toEqual("123");
|
||||
// expect(z.parse(a, true)).toEqual("true");
|
||||
// expect(() => z.parse(a, {})).toThrow();
|
||||
// });
|
||||
|
||||
test("z.optional", () => {
|
||||
const a = z.optional(z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string | undefined>();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, undefined)).toEqual(undefined);
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.nullable", () => {
|
||||
const a = z.nullable(z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string | null>();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, null)).toEqual(null);
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.default", () => {
|
||||
const a = z._default(z.string(), "default");
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, undefined)).toEqual("default");
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
|
||||
const b = z._default(z.string(), () => "default");
|
||||
expect(z.parse(b, undefined)).toEqual("default");
|
||||
expect(z.parse(b, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(b, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.catch", () => {
|
||||
const a = z.catch(z.string(), "default");
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, 123)).toEqual("default");
|
||||
|
||||
const b = z.catch(z.string(), () => "default");
|
||||
expect(z.parse(b, "hello")).toEqual("hello");
|
||||
expect(z.parse(b, 123)).toEqual("default");
|
||||
|
||||
const c = z.catch(z.string(), (ctx) => {
|
||||
return `${ctx.error.issues.length}issues`;
|
||||
});
|
||||
expect(z.parse(c, 1234)).toEqual("1issues");
|
||||
});
|
||||
|
||||
test("z.nan", () => {
|
||||
const a = z.nan();
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<number>();
|
||||
expect(z.parse(a, Number.NaN)).toEqual(Number.NaN);
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
expect(() => z.parse(a, "NaN")).toThrow();
|
||||
});
|
||||
|
||||
test("z.pipe", () => {
|
||||
const a = z.pipe(
|
||||
z.pipe(
|
||||
z.string(),
|
||||
z.transform((val) => val.length)
|
||||
),
|
||||
z.number()
|
||||
);
|
||||
type a_in = z.input<typeof a>;
|
||||
expectTypeOf<a_in>().toEqualTypeOf<string>();
|
||||
type a_out = z.output<typeof a>;
|
||||
expectTypeOf<a_out>().toEqualTypeOf<number>();
|
||||
|
||||
expect(z.parse(a, "123")).toEqual(3);
|
||||
expect(z.parse(a, "hello")).toEqual(5);
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.readonly", () => {
|
||||
const a = z.readonly(z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<Readonly<string>>();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.templateLiteral", () => {
|
||||
const a = z.templateLiteral([z.string(), z.number()]);
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<`${string}${number}`>();
|
||||
expect(z.parse(a, "hello123")).toEqual("hello123");
|
||||
expect(() => z.parse(a, "hello")).toThrow();
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
|
||||
// multipart
|
||||
const b = z.templateLiteral([z.string(), z.number(), z.string()]);
|
||||
type b = z.output<typeof b>;
|
||||
expectTypeOf<b>().toEqualTypeOf<`${string}${number}${string}`>();
|
||||
expect(z.parse(b, "hello123world")).toEqual("hello123world");
|
||||
expect(z.parse(b, "123")).toEqual("123");
|
||||
expect(() => z.parse(b, "hello")).toThrow();
|
||||
expect(() => z.parse(b, 123)).toThrow();
|
||||
|
||||
// include boolean
|
||||
const c = z.templateLiteral([z.string(), z.boolean()]);
|
||||
type c = z.output<typeof c>;
|
||||
expectTypeOf<c>().toEqualTypeOf<`${string}${boolean}`>();
|
||||
expect(z.parse(c, "hellotrue")).toEqual("hellotrue");
|
||||
expect(z.parse(c, "hellofalse")).toEqual("hellofalse");
|
||||
expect(() => z.parse(c, "hello")).toThrow();
|
||||
expect(() => z.parse(c, 123)).toThrow();
|
||||
|
||||
// include literal prefix
|
||||
const d = z.templateLiteral([z.literal("hello"), z.number()]);
|
||||
type d = z.output<typeof d>;
|
||||
expectTypeOf<d>().toEqualTypeOf<`hello${number}`>();
|
||||
expect(z.parse(d, "hello123")).toEqual("hello123");
|
||||
expect(() => z.parse(d, 123)).toThrow();
|
||||
expect(() => z.parse(d, "world123")).toThrow();
|
||||
|
||||
// include literal union
|
||||
const e = z.templateLiteral([z.literal(["aa", "bb"]), z.number()]);
|
||||
type e = z.output<typeof e>;
|
||||
expectTypeOf<e>().toEqualTypeOf<`aa${number}` | `bb${number}`>();
|
||||
expect(z.parse(e, "aa123")).toEqual("aa123");
|
||||
expect(z.parse(e, "bb123")).toEqual("bb123");
|
||||
expect(() => z.parse(e, "cc123")).toThrow();
|
||||
expect(() => z.parse(e, 123)).toThrow();
|
||||
});
|
||||
|
||||
// this returns both a schema and a check
|
||||
test("z.custom schema", () => {
|
||||
const a = z.custom((val) => {
|
||||
return typeof val === "string";
|
||||
});
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
test("z.custom check", () => {
|
||||
// @ts-expect-error Inference not possible, use z.refine()
|
||||
z.date().check(z.custom((val) => val.getTime() > 0));
|
||||
});
|
||||
|
||||
test("z.check", () => {
|
||||
// this is a more flexible version of z.custom that accepts an arbitrary _parse logic
|
||||
// the function should return base.$ZodResult
|
||||
const a = z.any().check(
|
||||
z.check<string>((ctx) => {
|
||||
if (typeof ctx.value === "string") return;
|
||||
ctx.issues.push({
|
||||
code: "custom",
|
||||
origin: "custom",
|
||||
message: "Expected a string",
|
||||
input: ctx.value,
|
||||
});
|
||||
})
|
||||
);
|
||||
expect(z.safeParse(a, "hello")).toMatchObject({
|
||||
success: true,
|
||||
data: "hello",
|
||||
});
|
||||
expect(z.safeParse(a, 123)).toMatchObject({
|
||||
success: false,
|
||||
error: { issues: [{ code: "custom", message: "Expected a string" }] },
|
||||
});
|
||||
});
|
||||
|
||||
test("z.with (alias for z.check)", () => {
|
||||
// .with() should work exactly the same as .check()
|
||||
const a = z.any().with(
|
||||
z.check<string>((ctx) => {
|
||||
if (typeof ctx.value === "string") return;
|
||||
ctx.issues.push({
|
||||
code: "custom",
|
||||
origin: "custom",
|
||||
message: "Expected a string",
|
||||
input: ctx.value,
|
||||
});
|
||||
})
|
||||
);
|
||||
expect(z.safeParse(a, "hello")).toMatchObject({
|
||||
success: true,
|
||||
data: "hello",
|
||||
});
|
||||
expect(z.safeParse(a, 123)).toMatchObject({
|
||||
success: false,
|
||||
error: { issues: [{ code: "custom", message: "Expected a string" }] },
|
||||
});
|
||||
|
||||
// Test with refine
|
||||
const b = z.string().with(z.refine((val) => val.length > 3, "Must be longer than 3"));
|
||||
expect(z.safeParse(b, "hello").success).toBe(true);
|
||||
expect(z.safeParse(b, "hi").success).toBe(false);
|
||||
|
||||
// Test with function
|
||||
const c = z.string().with(({ value, issues }) => {
|
||||
if (value.length <= 3) {
|
||||
issues.push({
|
||||
code: "custom",
|
||||
input: value,
|
||||
message: "Must be longer than 3",
|
||||
});
|
||||
}
|
||||
});
|
||||
expect(z.safeParse(c, "hello").success).toBe(true);
|
||||
expect(z.safeParse(c, "hi").success).toBe(false);
|
||||
});
|
||||
|
||||
test("z.instanceof", () => {
|
||||
class A {}
|
||||
|
||||
const a = z.instanceof(A);
|
||||
expect(z.parse(a, new A())).toBeInstanceOf(A);
|
||||
expect(() => z.parse(a, {})).toThrow();
|
||||
});
|
||||
|
||||
test("z.refine", () => {
|
||||
const a = z.number().check(
|
||||
z.refine((val) => val > 3),
|
||||
z.refine((val) => val < 10)
|
||||
);
|
||||
expect(z.parse(a, 5)).toEqual(5);
|
||||
expect(() => z.parse(a, 2)).toThrow();
|
||||
expect(() => z.parse(a, 11)).toThrow();
|
||||
expect(() => z.parse(a, "hi")).toThrow();
|
||||
});
|
||||
|
||||
// test("z.superRefine", () => {
|
||||
// const a = z.number([
|
||||
// z.superRefine((val, ctx) => {
|
||||
// if (val < 3) {
|
||||
// return ctx.addIssue({
|
||||
// code: "custom",
|
||||
// origin: "custom",
|
||||
// message: "Too small",
|
||||
// input: val,
|
||||
// });
|
||||
// }
|
||||
// if (val > 10) {
|
||||
// return ctx.addIssue("Too big");
|
||||
// }
|
||||
// }),
|
||||
// ]);
|
||||
|
||||
// expect(z.parse(a, 5)).toEqual(5);
|
||||
// expect(() => z.parse(a, 2)).toThrow();
|
||||
// expect(() => z.parse(a, 11)).toThrow();
|
||||
// expect(() => z.parse(a, "hi")).toThrow();
|
||||
// });
|
||||
|
||||
test("z.transform", () => {
|
||||
const a = z.transform((val: number) => {
|
||||
return `${val}`;
|
||||
});
|
||||
type a_in = z.input<typeof a>;
|
||||
expectTypeOf<a_in>().toEqualTypeOf<number>();
|
||||
type a_out = z.output<typeof a>;
|
||||
expectTypeOf<a_out>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, 123)).toEqual("123");
|
||||
});
|
||||
|
||||
test("z.$brand()", () => {
|
||||
const a = z.string().brand<"my-brand">();
|
||||
type a = z.output<typeof a>;
|
||||
const branded = (_: a) => {};
|
||||
// @ts-expect-error
|
||||
branded("asdf");
|
||||
});
|
||||
|
||||
test("z.lazy", () => {
|
||||
const a = z.lazy(() => z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<string>();
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(() => z.parse(a, 123)).toThrow();
|
||||
});
|
||||
|
||||
// schema that validates JSON-like data
|
||||
test("z.json", () => {
|
||||
const a = z.json();
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<util.JSONType>();
|
||||
|
||||
expect(z.parse(a, "hello")).toEqual("hello");
|
||||
expect(z.parse(a, 123)).toEqual(123);
|
||||
expect(z.parse(a, true)).toEqual(true);
|
||||
expect(z.parse(a, null)).toEqual(null);
|
||||
expect(z.parse(a, {})).toEqual({});
|
||||
expect(z.parse(a, { a: "hello" })).toEqual({ a: "hello" });
|
||||
expect(z.parse(a, [1, 2, 3])).toEqual([1, 2, 3]);
|
||||
expect(z.parse(a, [{ a: "hello" }])).toEqual([{ a: "hello" }]);
|
||||
|
||||
// fail cases
|
||||
expect(() => z.parse(a, new Date())).toThrow();
|
||||
expect(() => z.parse(a, Symbol())).toThrow();
|
||||
expect(() => z.parse(a, { a: new Date() })).toThrow();
|
||||
expect(() => z.parse(a, undefined)).toThrow();
|
||||
expect(() => z.parse(a, { a: undefined })).toThrow();
|
||||
});
|
||||
|
||||
// promise
|
||||
test("z.promise", async () => {
|
||||
const a = z.promise(z.string());
|
||||
type a = z.output<typeof a>;
|
||||
expectTypeOf<a>().toEqualTypeOf<Promise<string>>();
|
||||
|
||||
expect(await z.safeParseAsync(a, Promise.resolve("hello"))).toMatchObject({
|
||||
success: true,
|
||||
data: "hello",
|
||||
});
|
||||
expect(await z.safeParseAsync(a, Promise.resolve(123))).toMatchObject({
|
||||
success: false,
|
||||
});
|
||||
|
||||
const b = z.string();
|
||||
expect(() => z.parse(b, Promise.resolve("hello"))).toThrow();
|
||||
});
|
||||
// test("type assertions", () => {
|
||||
// const schema = z.pipe(
|
||||
// z.string(),
|
||||
// z.transform((val) => val.length)
|
||||
// );
|
||||
// schema.assertInput<string>();
|
||||
// // @ts-expect-error
|
||||
// schema.assertInput<number>();
|
||||
|
||||
// schema.assertOutput<number>();
|
||||
// // @ts-expect-error
|
||||
// schema.assertOutput<string>();
|
||||
// });
|
||||
|
||||
test("isPlainObject", () => {
|
||||
expect(z.core.util.isPlainObject({})).toEqual(true);
|
||||
expect(z.core.util.isPlainObject(Object.create(null))).toEqual(true);
|
||||
expect(z.core.util.isPlainObject([])).toEqual(false);
|
||||
expect(z.core.util.isPlainObject(new Date())).toEqual(false);
|
||||
expect(z.core.util.isPlainObject(null)).toEqual(false);
|
||||
expect(z.core.util.isPlainObject(undefined)).toEqual(false);
|
||||
expect(z.core.util.isPlainObject("string")).toEqual(false);
|
||||
expect(z.core.util.isPlainObject(123)).toEqual(false);
|
||||
expect(z.core.util.isPlainObject(Symbol())).toEqual(false);
|
||||
expect(z.core.util.isPlainObject({ constructor: "string" })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: 123 })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: null })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: undefined })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: true })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: {} })).toEqual(true);
|
||||
expect(z.core.util.isPlainObject({ constructor: [] })).toEqual(true);
|
||||
});
|
||||
|
||||
test("shallowClone with constructor field", () => {
|
||||
const objWithConstructor = { constructor: "string", key: "value" };
|
||||
const cloned = z.core.util.shallowClone(objWithConstructor);
|
||||
|
||||
expect(cloned).toEqual(objWithConstructor);
|
||||
expect(cloned).not.toBe(objWithConstructor);
|
||||
expect(cloned.constructor).toBe("string");
|
||||
expect(cloned.key).toBe("value");
|
||||
|
||||
const testCases = [
|
||||
{ constructor: 123, data: "test" },
|
||||
{ constructor: null, data: "test" },
|
||||
{ constructor: true, data: "test" },
|
||||
{ constructor: {}, data: "test" },
|
||||
{ constructor: [], data: "test" },
|
||||
];
|
||||
|
||||
for (const testCase of testCases) {
|
||||
const clonedCase = z.core.util.shallowClone(testCase);
|
||||
expect(clonedCase).toEqual(testCase);
|
||||
expect(clonedCase).not.toBe(testCase);
|
||||
}
|
||||
});
|
||||
|
||||
test("def typing", () => {
|
||||
z.string().def.type satisfies "string";
|
||||
z.number().def.type satisfies "number";
|
||||
z.bigint().def.type satisfies "bigint";
|
||||
z.boolean().def.type satisfies "boolean";
|
||||
z.date().def.type satisfies "date";
|
||||
z.symbol().def.type satisfies "symbol";
|
||||
z.undefined().def.type satisfies "undefined";
|
||||
z.string().nullable().def.type satisfies "nullable";
|
||||
z.null().def.type satisfies "null";
|
||||
z.any().def.type satisfies "any";
|
||||
z.unknown().def.type satisfies "unknown";
|
||||
z.never().def.type satisfies "never";
|
||||
z.void().def.type satisfies "void";
|
||||
z.array(z.string()).def.type satisfies "array";
|
||||
z.object({ key: z.string() }).def.type satisfies "object";
|
||||
z.union([z.string(), z.number()]).def.type satisfies "union";
|
||||
z.intersection(z.string(), z.number()).def.type satisfies "intersection";
|
||||
z.tuple([z.string(), z.number()]).def.type satisfies "tuple";
|
||||
z.record(z.string(), z.number()).def.type satisfies "record";
|
||||
z.map(z.string(), z.number()).def.type satisfies "map";
|
||||
z.set(z.string()).def.type satisfies "set";
|
||||
z.literal("example").def.type satisfies "literal";
|
||||
z.enum(["a", "b", "c"]).def.type satisfies "enum";
|
||||
z.promise(z.string()).def.type satisfies "promise";
|
||||
z.lazy(() => z.string()).def.type satisfies "lazy";
|
||||
z.string().optional().def.type satisfies "optional";
|
||||
z.string().default("default").def.type satisfies "default";
|
||||
z.templateLiteral([z.literal("a"), z.literal("b")]).def.type satisfies "template_literal";
|
||||
z.custom<string>((val) => typeof val === "string").def.type satisfies "custom";
|
||||
z.transform((val) => val as string).def.type satisfies "transform";
|
||||
z.string().optional().nonoptional().def.type satisfies "nonoptional";
|
||||
z.object({ key: z.string() }).readonly().def.type satisfies "readonly";
|
||||
z.nan().def.type satisfies "nan";
|
||||
z.unknown().pipe(z.number()).def.type satisfies "pipe";
|
||||
z.success(z.string()).def.type satisfies "success";
|
||||
z.string().catch("fallback").def.type satisfies "catch";
|
||||
z.file().def.type satisfies "file";
|
||||
});
|
||||
|
||||
test("runtime type property exists and returns correct values", () => {
|
||||
const stringSchema = z.string();
|
||||
expect(stringSchema.type).toBe("string");
|
||||
});
|
||||
|
||||
test("type narrowing works with type property", () => {
|
||||
type ArrayOrRecord = z.ZodArray<z.ZodString> | z.ZodRecord<z.ZodString, z.ZodAny>;
|
||||
const arraySchema = z.array(z.string()) as ArrayOrRecord;
|
||||
|
||||
if (arraySchema.type === "array") {
|
||||
expectTypeOf(arraySchema).toEqualTypeOf<z.ZodArray<z.ZodString>>();
|
||||
expect(arraySchema.element).toBeDefined();
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* @fileoverview The CodePathSegment class.
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const debug = require("./debug-helpers");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether or not a given segment is reachable.
|
||||
* @param {CodePathSegment} segment A segment to check.
|
||||
* @returns {boolean} `true` if the segment is reachable.
|
||||
*/
|
||||
function isReachable(segment) {
|
||||
return segment.reachable;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A code path segment.
|
||||
*
|
||||
* Each segment is arranged in a series of linked lists (implemented by arrays)
|
||||
* that keep track of the previous and next segments in a code path. In this way,
|
||||
* you can navigate between all segments in any code path so long as you have a
|
||||
* reference to any segment in that code path.
|
||||
*
|
||||
* When first created, the segment is in a detached state, meaning that it knows the
|
||||
* segments that came before it but those segments don't know that this new segment
|
||||
* follows it. Only when `CodePathSegment#markUsed()` is called on a segment does it
|
||||
* officially become part of the code path by updating the previous segments to know
|
||||
* that this new segment follows.
|
||||
*/
|
||||
class CodePathSegment {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} id An identifier.
|
||||
* @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
|
||||
* This array includes unreachable segments.
|
||||
* @param {boolean} reachable A flag which shows this is reachable.
|
||||
*/
|
||||
constructor(id, allPrevSegments, reachable) {
|
||||
/**
|
||||
* The identifier of this code path.
|
||||
* Rules use it to store additional information of each rule.
|
||||
* @type {string}
|
||||
*/
|
||||
this.id = id;
|
||||
|
||||
/**
|
||||
* An array of the next reachable segments.
|
||||
* @type {CodePathSegment[]}
|
||||
*/
|
||||
this.nextSegments = [];
|
||||
|
||||
/**
|
||||
* An array of the previous reachable segments.
|
||||
* @type {CodePathSegment[]}
|
||||
*/
|
||||
this.prevSegments = allPrevSegments.filter(isReachable);
|
||||
|
||||
/**
|
||||
* An array of all next segments including reachable and unreachable.
|
||||
* @type {CodePathSegment[]}
|
||||
*/
|
||||
this.allNextSegments = [];
|
||||
|
||||
/**
|
||||
* An array of all previous segments including reachable and unreachable.
|
||||
* @type {CodePathSegment[]}
|
||||
*/
|
||||
this.allPrevSegments = allPrevSegments;
|
||||
|
||||
/**
|
||||
* A flag which shows this is reachable.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.reachable = reachable;
|
||||
|
||||
// Internal data.
|
||||
Object.defineProperty(this, "internal", {
|
||||
value: {
|
||||
// determines if the segment has been attached to the code path
|
||||
used: false,
|
||||
|
||||
// array of previous segments coming from the end of a loop
|
||||
loopedPrevSegments: [],
|
||||
},
|
||||
});
|
||||
|
||||
/* c8 ignore start */
|
||||
if (debug.enabled) {
|
||||
this.internal.nodes = [];
|
||||
} /* c8 ignore stop */
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a given previous segment is coming from the end of a loop.
|
||||
* @param {CodePathSegment} segment A previous segment to check.
|
||||
* @returns {boolean} `true` if the segment is coming from the end of a loop.
|
||||
*/
|
||||
isLoopedPrevSegment(segment) {
|
||||
return this.internal.loopedPrevSegments.includes(segment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the root segment.
|
||||
* @param {string} id An identifier.
|
||||
* @returns {CodePathSegment} The created segment.
|
||||
*/
|
||||
static newRoot(id) {
|
||||
return new CodePathSegment(id, [], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new segment and appends it after the given segments.
|
||||
* @param {string} id An identifier.
|
||||
* @param {CodePathSegment[]} allPrevSegments An array of the previous segments
|
||||
* to append to.
|
||||
* @returns {CodePathSegment} The created segment.
|
||||
*/
|
||||
static newNext(id, allPrevSegments) {
|
||||
return new CodePathSegment(
|
||||
id,
|
||||
CodePathSegment.flattenUnusedSegments(allPrevSegments),
|
||||
allPrevSegments.some(isReachable),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an unreachable segment and appends it after the given segments.
|
||||
* @param {string} id An identifier.
|
||||
* @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
|
||||
* @returns {CodePathSegment} The created segment.
|
||||
*/
|
||||
static newUnreachable(id, allPrevSegments) {
|
||||
const segment = new CodePathSegment(
|
||||
id,
|
||||
CodePathSegment.flattenUnusedSegments(allPrevSegments),
|
||||
false,
|
||||
);
|
||||
|
||||
/*
|
||||
* In `if (a) return a; foo();` case, the unreachable segment preceded by
|
||||
* the return statement is not used but must not be removed.
|
||||
*/
|
||||
CodePathSegment.markUsed(segment);
|
||||
|
||||
return segment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a segment that follows given segments.
|
||||
* This factory method does not connect with `allPrevSegments`.
|
||||
* But this inherits `reachable` flag.
|
||||
* @param {string} id An identifier.
|
||||
* @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
|
||||
* @returns {CodePathSegment} The created segment.
|
||||
*/
|
||||
static newDisconnected(id, allPrevSegments) {
|
||||
return new CodePathSegment(id, [], allPrevSegments.some(isReachable));
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a given segment as used.
|
||||
*
|
||||
* And this function registers the segment into the previous segments as a next.
|
||||
* @param {CodePathSegment} segment A segment to mark.
|
||||
* @returns {void}
|
||||
*/
|
||||
static markUsed(segment) {
|
||||
if (segment.internal.used) {
|
||||
return;
|
||||
}
|
||||
segment.internal.used = true;
|
||||
|
||||
let i;
|
||||
|
||||
if (segment.reachable) {
|
||||
/*
|
||||
* If the segment is reachable, then it's officially part of the
|
||||
* code path. This loops through all previous segments to update
|
||||
* their list of next segments. Because the segment is reachable,
|
||||
* it's added to both `nextSegments` and `allNextSegments`.
|
||||
*/
|
||||
for (i = 0; i < segment.allPrevSegments.length; ++i) {
|
||||
const prevSegment = segment.allPrevSegments[i];
|
||||
|
||||
prevSegment.allNextSegments.push(segment);
|
||||
prevSegment.nextSegments.push(segment);
|
||||
}
|
||||
} else {
|
||||
/*
|
||||
* If the segment is not reachable, then it's not officially part of the
|
||||
* code path. This loops through all previous segments to update
|
||||
* their list of next segments. Because the segment is not reachable,
|
||||
* it's added only to `allNextSegments`.
|
||||
*/
|
||||
for (i = 0; i < segment.allPrevSegments.length; ++i) {
|
||||
segment.allPrevSegments[i].allNextSegments.push(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a previous segment as looped.
|
||||
* @param {CodePathSegment} segment A segment.
|
||||
* @param {CodePathSegment} prevSegment A previous segment to mark.
|
||||
* @returns {void}
|
||||
*/
|
||||
static markPrevSegmentAsLooped(segment, prevSegment) {
|
||||
segment.internal.loopedPrevSegments.push(prevSegment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new array based on an array of segments. If any segment in the
|
||||
* array is unused, then it is replaced by all of its previous segments.
|
||||
* All used segments are returned as-is without replacement.
|
||||
* @param {CodePathSegment[]} segments The array of segments to flatten.
|
||||
* @returns {CodePathSegment[]} The flattened array.
|
||||
*/
|
||||
static flattenUnusedSegments(segments) {
|
||||
const done = new Set();
|
||||
|
||||
for (let i = 0; i < segments.length; ++i) {
|
||||
const segment = segments[i];
|
||||
|
||||
// Ignores duplicated.
|
||||
if (done.has(segment)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Use previous segments if unused.
|
||||
if (!segment.internal.used) {
|
||||
for (let j = 0; j < segment.allPrevSegments.length; ++j) {
|
||||
const prevSegment = segment.allPrevSegments[j];
|
||||
|
||||
if (!done.has(prevSegment)) {
|
||||
done.add(prevSegment);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
done.add(segment);
|
||||
}
|
||||
}
|
||||
|
||||
return [...done];
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CodePathSegment;
|
||||
@@ -0,0 +1,146 @@
|
||||
/*! *****************************************************************************
|
||||
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.iterable" />
|
||||
|
||||
// NOTE: This is specified as what is essentially an unreachable module. All actual global declarations can be found
|
||||
// in the `declare global` section, below. This is necessary as there is currently no way to declare an `abstract`
|
||||
// member without declaring a `class`, but declaring `class Iterator<T>` globally would conflict with TypeScript's
|
||||
// general purpose `Iterator<T>` interface.
|
||||
export {};
|
||||
|
||||
// Abstract type that allows us to mark `next` as `abstract`
|
||||
declare abstract class Iterator<T, TResult = undefined, TNext = unknown> { // eslint-disable-line @typescript-eslint/no-unsafe-declaration-merging
|
||||
abstract next(value?: TNext): IteratorResult<T, TResult>;
|
||||
}
|
||||
|
||||
// Merge all members of `IteratorObject<T>` into `Iterator<T>`
|
||||
interface Iterator<T, TResult, TNext> extends globalThis.IteratorObject<T, TResult, TNext> {}
|
||||
|
||||
// Capture the `Iterator` constructor in a type we can use in the `extends` clause of `IteratorConstructor`.
|
||||
type IteratorObjectConstructor = typeof Iterator;
|
||||
|
||||
declare global {
|
||||
// Global `IteratorObject<T, TReturn, TNext>` interface that can be augmented by polyfills
|
||||
interface IteratorObject<T, TReturn, TNext> {
|
||||
/**
|
||||
* Returns this iterator.
|
||||
*/
|
||||
[Symbol.iterator](): IteratorObject<T, TReturn, TNext>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are the result of applying the callback to the values from this iterator.
|
||||
* @param callbackfn A function that accepts up to two arguments to be used to transform values from the underlying iterator.
|
||||
*/
|
||||
map<U>(callbackfn: (value: T, index: number) => U): IteratorObject<U, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
|
||||
* @param predicate A function that accepts up to two arguments to be used to test values from the underlying iterator.
|
||||
*/
|
||||
filter<S extends T>(predicate: (value: T, index: number) => value is S): IteratorObject<S, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
|
||||
* @param predicate A function that accepts up to two arguments to be used to test values from the underlying iterator.
|
||||
*/
|
||||
filter(predicate: (value: T, index: number) => unknown): IteratorObject<T, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached.
|
||||
* @param limit The maximum number of values to yield.
|
||||
*/
|
||||
take(limit: number): IteratorObject<T, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are the values from this iterator after skipping the provided count.
|
||||
* @param count The number of values to drop.
|
||||
*/
|
||||
drop(count: number): IteratorObject<T, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables.
|
||||
* @param callback A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result.
|
||||
*/
|
||||
flatMap<U>(callback: (value: T, index: number) => Iterator<U, unknown, undefined> | Iterable<U, unknown, undefined>): IteratorObject<U, undefined, unknown>;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in this iterator. 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 three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
|
||||
* @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 a value from the iterator.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T;
|
||||
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in this iterator. 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 three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
|
||||
* @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 a value from the iterator.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Creates a new array from the values yielded by this iterator.
|
||||
*/
|
||||
toArray(): T[];
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in the iterator.
|
||||
* @param callbackfn A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator.
|
||||
*/
|
||||
forEach(callbackfn: (value: T, index: number) => void): void;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of this iterator.
|
||||
* @param predicate A function that accepts up to two arguments. The some method calls
|
||||
* the predicate function for each element in this iterator until the predicate returns a value
|
||||
* true, or until the end of the iterator.
|
||||
*/
|
||||
some(predicate: (value: T, index: number) => unknown): boolean;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of this iterator satisfy the specified test.
|
||||
* @param predicate A function that accepts up to two arguments. The every method calls
|
||||
* the predicate function for each element in this iterator until the predicate returns
|
||||
* false, or until the end of this iterator.
|
||||
*/
|
||||
every(predicate: (value: T, index: number) => unknown): boolean;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in this iterator where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of this iterator, in
|
||||
* 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.
|
||||
*/
|
||||
find<S extends T>(predicate: (value: T, index: number) => value is S): S | undefined;
|
||||
find(predicate: (value: T, index: number) => unknown): T | undefined;
|
||||
|
||||
readonly [Symbol.toStringTag]: string;
|
||||
}
|
||||
|
||||
// Global `IteratorConstructor` interface that can be augmented by polyfills
|
||||
interface IteratorConstructor extends IteratorObjectConstructor {
|
||||
/**
|
||||
* Creates a native iterator from an iterator or iterable object.
|
||||
* Returns its input if the input already inherits from the built-in Iterator class.
|
||||
* @param value An iterator or iterable object to convert a native iterator.
|
||||
*/
|
||||
from<T>(value: Iterator<T, unknown, undefined> | Iterable<T, unknown, undefined>): IteratorObject<T, undefined, unknown>;
|
||||
}
|
||||
|
||||
var Iterator: IteratorConstructor;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "acorn-jsx",
|
||||
"description": "Modern, fast React.js JSX parser",
|
||||
"homepage": "https://github.com/acornjs/acorn-jsx",
|
||||
"version": "5.3.2",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Ingvar Stepanyan",
|
||||
"email": "me@rreverser.com",
|
||||
"web": "http://rreverser.com/"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/acornjs/acorn-jsx"
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "node test/run.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"acorn": "^8.0.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4oBG;AACH,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC"}
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
|
||||
// npx nx generate-lib repo
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.es2024_arraybuffer = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
exports.es2024_arraybuffer = {
|
||||
libs: [],
|
||||
variables: [
|
||||
['ArrayBuffer', base_config_1.TYPE],
|
||||
['ArrayBufferConstructor', base_config_1.TYPE],
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
# file-entry-cache
|
||||
> Super simple cache for file metadata, useful for process that work on a given series of files
|
||||
> and that only need to repeat the job on the changed ones since the previous run of the process — Edit
|
||||
|
||||
[](https://npmjs.org/package/file-entry-cache)
|
||||
[](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml)
|
||||
[](https://codecov.io/github/jaredwray/file-entry-cache)
|
||||
[](https://npmjs.com/package/file-entry-cache)
|
||||
|
||||
|
||||
## install
|
||||
|
||||
```bash
|
||||
npm i --save file-entry-cache
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The module exposes two functions `create` and `createFromFile`.
|
||||
|
||||
## `create(cacheName, [directory, useCheckSum])`
|
||||
- **cacheName**: the name of the cache to be created
|
||||
- **directory**: Optional the directory to load the cache from
|
||||
- **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file.
|
||||
|
||||
## `createFromFile(pathToCache, [useCheckSum])`
|
||||
- **pathToCache**: the path to the cache file (this combines the cache name and directory)
|
||||
- **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file.
|
||||
|
||||
```js
|
||||
// loads the cache, if one does not exists for the given
|
||||
// Id a new one will be prepared to be created
|
||||
var fileEntryCache = require('file-entry-cache');
|
||||
|
||||
var cache = fileEntryCache.create('testCache');
|
||||
|
||||
var files = expand('../fixtures/*.txt');
|
||||
|
||||
// the first time this method is called, will return all the files
|
||||
var oFiles = cache.getUpdatedFiles(files);
|
||||
|
||||
// this will persist this to disk checking each file stats and
|
||||
// updating the meta attributes `size` and `mtime`.
|
||||
// custom fields could also be added to the meta object and will be persisted
|
||||
// in order to retrieve them later
|
||||
cache.reconcile();
|
||||
|
||||
// use this if you want the non visited file entries to be kept in the cache
|
||||
// for more than one execution
|
||||
//
|
||||
// cache.reconcile( true /* noPrune */)
|
||||
|
||||
// on a second run
|
||||
var cache2 = fileEntryCache.create('testCache');
|
||||
|
||||
// will return now only the files that were modified or none
|
||||
// if no files were modified previous to the execution of this function
|
||||
var oFiles = cache.getUpdatedFiles(files);
|
||||
|
||||
// if you want to prevent a file from being considered non modified
|
||||
// something useful if a file failed some sort of validation
|
||||
// you can then remove the entry from the cache doing
|
||||
cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles`
|
||||
// that will effectively make the file to appear again as modified until the validation is passed. In that
|
||||
// case you should not remove it from the cache
|
||||
|
||||
// if you need all the files, so you can determine what to do with the changed ones
|
||||
// you can call
|
||||
var oFiles = cache.normalizeEntries(files);
|
||||
|
||||
// oFiles will be an array of objects like the following
|
||||
entry = {
|
||||
key: 'some/name/file', the path to the file
|
||||
changed: true, // if the file was changed since previous run
|
||||
meta: {
|
||||
size: 3242, // the size of the file
|
||||
mtime: 231231231, // the modification time of the file
|
||||
data: {} // some extra field stored for this file (useful to save the result of a transformation on the file
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Motivation for this module
|
||||
|
||||
I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make
|
||||
a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run.
|
||||
|
||||
In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second.
|
||||
|
||||
This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with
|
||||
optional file persistance.
|
||||
|
||||
The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed,
|
||||
then store the new state of the files. The next time this module request for `getChangedFiles` will return only
|
||||
the files that were modified. Making the process to end faster.
|
||||
|
||||
This module could also be used by processes that modify the files applying a transform, in that case the result of the
|
||||
transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted.
|
||||
Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the
|
||||
entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed
|
||||
the transformed stored data could be used instead of actually applying the transformation, saving time in case of only
|
||||
a few files changed.
|
||||
|
||||
In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed.
|
||||
|
||||
## Important notes
|
||||
- The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values
|
||||
- All the changes to the cache state are done to memory first and only persisted after reconcile.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
|
||||
Reference in New Issue
Block a user