feat(auth): implement user authentication system

This commit is contained in:
J.A.R.V.I.S. 2026-03-19 23:10:50 +00:00
parent 4847ab793a
commit 25cea4fbe8
12051 changed files with 1462377 additions and 0 deletions

21
backend/node_modules/jest-cli/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.

11
backend/node_modules/jest-cli/README.md generated vendored Normal file
View file

@ -0,0 +1,11 @@
# Jest
🃏 Delightful JavaScript Testing
- **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project.
- **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files.
- **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing.
Read More: https://jestjs.io/

17
backend/node_modules/jest-cli/bin/jest.js generated vendored Executable file
View file

@ -0,0 +1,17 @@
#!/usr/bin/env node
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const importLocal = require('import-local');
if (!importLocal(__filename)) {
if (process.env.NODE_ENV == null) {
process.env.NODE_ENV = 'test';
}
require('..').run();
}

731
backend/node_modules/jest-cli/build/args.js generated vendored Normal file
View file

@ -0,0 +1,731 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.check = check;
exports.usage = exports.options = exports.docs = void 0;
function _jestConfig() {
const data = require('jest-config');
_jestConfig = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function check(argv) {
if (
argv.runInBand &&
Object.prototype.hasOwnProperty.call(argv, 'maxWorkers')
) {
throw new Error(
'Both --runInBand and --maxWorkers were specified, only one is allowed.'
);
}
for (const key of [
'onlyChanged',
'lastCommit',
'changedFilesWithAncestor',
'changedSince'
]) {
if (argv[key] && argv.watchAll) {
throw new Error(
`Both --${key} and --watchAll were specified, but cannot be used ` +
'together. Try the --watch option which reruns only tests ' +
'related to changed files.'
);
}
}
if (argv.onlyFailures && argv.watchAll) {
throw new Error(
'Both --onlyFailures and --watchAll were specified, only one is allowed.'
);
}
if (argv.findRelatedTests && argv._.length === 0) {
throw new Error(
'The --findRelatedTests option requires file paths to be specified.\n' +
'Example usage: jest --findRelatedTests ./src/source.js ' +
'./src/index.js.'
);
}
if (
Object.prototype.hasOwnProperty.call(argv, 'maxWorkers') &&
argv.maxWorkers === undefined
) {
throw new Error(
'The --maxWorkers (-w) option requires a number or string to be specified.\n' +
'Example usage: jest --maxWorkers 2\n' +
'Example usage: jest --maxWorkers 50%\n' +
'Or did you mean --watch?'
);
}
if (argv.selectProjects && argv.selectProjects.length === 0) {
throw new Error(
'The --selectProjects option requires the name of at least one project to be specified.\n' +
'Example usage: jest --selectProjects my-first-project my-second-project'
);
}
if (argv.ignoreProjects && argv.ignoreProjects.length === 0) {
throw new Error(
'The --ignoreProjects option requires the name of at least one project to be specified.\n' +
'Example usage: jest --ignoreProjects my-first-project my-second-project'
);
}
if (
argv.config &&
!(0, _jestConfig().isJSONString)(argv.config) &&
!argv.config.match(
new RegExp(
`\\.(${_jestConfig()
.constants.JEST_CONFIG_EXT_ORDER.map(e => e.substring(1))
.join('|')})$`,
'i'
)
)
) {
throw new Error(
`The --config option requires a JSON string literal, or a file path with one of these extensions: ${_jestConfig().constants.JEST_CONFIG_EXT_ORDER.join(
', '
)}.\nExample usage: jest --config ./jest.config.js`
);
}
return true;
}
const usage = 'Usage: $0 [--config=<pathToConfigFile>] [TestPathPattern]';
exports.usage = usage;
const docs = 'Documentation: https://jestjs.io/';
// The default values are all set in jest-config
exports.docs = docs;
const options = {
all: {
description:
'The opposite of `onlyChanged`. If `onlyChanged` is set by ' +
'default, running jest with `--all` will force Jest to run all tests ' +
'instead of running only tests related to changed files.',
type: 'boolean'
},
automock: {
description: 'Automock all files by default.',
type: 'boolean'
},
bail: {
alias: 'b',
description:
'Exit the test suite immediately after `n` number of failing tests.',
type: 'boolean'
},
cache: {
description:
'Whether to use the transform cache. Disable the cache ' +
'using --no-cache.',
type: 'boolean'
},
cacheDirectory: {
description:
'The directory where Jest should store its cached ' +
' dependency information.',
type: 'string'
},
changedFilesWithAncestor: {
description:
'Runs tests related to the current changes and the changes made in the ' +
'last commit. Behaves similarly to `--onlyChanged`.',
type: 'boolean'
},
changedSince: {
description:
'Runs tests related to the changes since the provided branch. If the ' +
'current branch has diverged from the given branch, then only changes ' +
'made locally will be tested. Behaves similarly to `--onlyChanged`.',
nargs: 1,
type: 'string'
},
ci: {
description:
'Whether to run Jest in continuous integration (CI) mode. ' +
'This option is on by default in most popular CI environments. It will ' +
'prevent snapshots from being written unless explicitly requested.',
type: 'boolean'
},
clearCache: {
description:
'Clears the configured Jest cache directory and then exits. ' +
'Default directory can be found by calling jest --showConfig',
type: 'boolean'
},
clearMocks: {
description:
'Automatically clear mock calls, instances, contexts and results before every test. ' +
'Equivalent to calling jest.clearAllMocks() before each test.',
type: 'boolean'
},
collectCoverage: {
description: 'Alias for --coverage.',
type: 'boolean'
},
collectCoverageFrom: {
description:
'A glob pattern relative to <rootDir> matching the files that coverage ' +
'info needs to be collected from.',
type: 'string'
},
color: {
description:
'Forces test results output color highlighting (even if ' +
'stdout is not a TTY). Set to false if you would like to have no colors.',
type: 'boolean'
},
colors: {
description: 'Alias for `--color`.',
type: 'boolean'
},
config: {
alias: 'c',
description:
'The path to a jest config file specifying how to find ' +
'and execute tests. If no rootDir is set in the config, the directory ' +
'containing the config file is assumed to be the rootDir for the project. ' +
'This can also be a JSON encoded value which Jest will use as configuration.',
type: 'string'
},
coverage: {
description:
'Indicates that test coverage information should be ' +
'collected and reported in the output.',
type: 'boolean'
},
coverageDirectory: {
description: 'The directory where Jest should output its coverage files.',
type: 'string'
},
coveragePathIgnorePatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all file paths before executing the test. If the file path ' +
'matches any of the patterns, coverage information will be skipped.',
string: true,
type: 'array'
},
coverageProvider: {
choices: ['babel', 'v8'],
description: 'Select between Babel and V8 to collect coverage'
},
coverageReporters: {
description:
'A list of reporter names that Jest uses when writing ' +
'coverage reports. Any istanbul reporter can be used.',
string: true,
type: 'array'
},
coverageThreshold: {
description:
'A JSON string with which will be used to configure ' +
'minimum threshold enforcement for coverage results',
type: 'string'
},
debug: {
description: 'Print debugging info about your jest config.',
type: 'boolean'
},
detectLeaks: {
description:
'**EXPERIMENTAL**: Detect memory leaks in tests. After executing a ' +
'test, it will try to garbage collect the global object used, and fail ' +
'if it was leaked',
type: 'boolean'
},
detectOpenHandles: {
description:
'Print out remaining open handles preventing Jest from exiting at the ' +
'end of a test run. Implies `runInBand`.',
type: 'boolean'
},
env: {
description:
'The test environment used for all tests. This can point to ' +
'any file or node module. Examples: `jsdom`, `node` or ' +
'`path/to/my-environment.js`',
type: 'string'
},
errorOnDeprecated: {
description: 'Make calling deprecated APIs throw helpful error messages.',
type: 'boolean'
},
expand: {
alias: 'e',
description: 'Use this flag to show full diffs instead of a patch.',
type: 'boolean'
},
filter: {
description:
'Path to a module exporting a filtering function. This method receives ' +
'a list of tests which can be manipulated to exclude tests from ' +
'running. Especially useful when used in conjunction with a testing ' +
'infrastructure to filter known broken tests.',
type: 'string'
},
findRelatedTests: {
description:
'Find related tests for a list of source files that were ' +
'passed in as arguments. Useful for pre-commit hook integration to run ' +
'the minimal amount of tests necessary.',
type: 'boolean'
},
forceExit: {
description:
'Force Jest to exit after all tests have completed running. ' +
'This is useful when resources set up by test code cannot be ' +
'adequately cleaned up.',
type: 'boolean'
},
globalSetup: {
description: 'The path to a module that runs before All Tests.',
type: 'string'
},
globalTeardown: {
description: 'The path to a module that runs after All Tests.',
type: 'string'
},
globals: {
description:
'A JSON string with map of global variables that need ' +
'to be available in all test environments.',
type: 'string'
},
haste: {
description:
'A JSON string with map of variables for the haste module system',
type: 'string'
},
ignoreProjects: {
description:
'Ignore the tests of the specified projects. ' +
'Jest uses the attribute `displayName` in the configuration to identify each project.',
string: true,
type: 'array'
},
init: {
description: 'Generate a basic configuration file',
type: 'boolean'
},
injectGlobals: {
description: 'Should Jest inject global variables or not',
type: 'boolean'
},
json: {
description:
'Prints the test results in JSON. This mode will send all ' +
'other test output and user messages to stderr.',
type: 'boolean'
},
lastCommit: {
description:
'Run all tests affected by file changes in the last commit made. ' +
'Behaves similarly to `--onlyChanged`.',
type: 'boolean'
},
listTests: {
description:
'Lists all tests Jest will run given the arguments and ' +
'exits. Most useful in a CI system together with `--findRelatedTests` ' +
'to determine the tests Jest will run based on specific files',
type: 'boolean'
},
logHeapUsage: {
description:
'Logs the heap usage after every test. Useful to debug ' +
'memory leaks. Use together with `--runInBand` and `--expose-gc` in ' +
'node.',
type: 'boolean'
},
maxConcurrency: {
description:
'Specifies the maximum number of tests that are allowed to run ' +
'concurrently. This only affects tests using `test.concurrent`.',
type: 'number'
},
maxWorkers: {
alias: 'w',
description:
'Specifies the maximum number of workers the worker-pool ' +
'will spawn for running tests. This defaults to the number of the ' +
'cores available on your machine. (its usually best not to override ' +
'this default)',
type: 'string'
},
moduleDirectories: {
description:
'An array of directory names to be searched recursively ' +
"up from the requiring module's location.",
string: true,
type: 'array'
},
moduleFileExtensions: {
description:
'An array of file extensions your modules use. If you ' +
'require modules without specifying a file extension, these are the ' +
'extensions Jest will look for.',
string: true,
type: 'array'
},
moduleNameMapper: {
description:
'A JSON string with a map from regular expressions to ' +
'module names or to arrays of module names that allow to stub ' +
'out resources, like images or styles with a single module',
type: 'string'
},
modulePathIgnorePatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all module paths before those paths are to be considered ' +
'"visible" to the module loader.',
string: true,
type: 'array'
},
modulePaths: {
description:
'An alternative API to setting the NODE_PATH env variable, ' +
'modulePaths is an array of absolute paths to additional locations to ' +
'search when resolving modules.',
string: true,
type: 'array'
},
noStackTrace: {
description: 'Disables stack trace in test results output',
type: 'boolean'
},
notify: {
description: 'Activates notifications for test results.',
type: 'boolean'
},
notifyMode: {
description: 'Specifies when notifications will appear for test results.',
type: 'string'
},
onlyChanged: {
alias: 'o',
description:
'Attempts to identify which tests to run based on which ' +
"files have changed in the current repository. Only works if you're " +
'running tests in a git or hg repository at the moment.',
type: 'boolean'
},
onlyFailures: {
alias: 'f',
description: 'Run tests that failed in the previous execution.',
type: 'boolean'
},
openHandlesTimeout: {
description:
'Print a warning about probable open handles if Jest does not exit ' +
'cleanly after this number of milliseconds. `0` to disable.',
type: 'number'
},
outputFile: {
description:
'Write test results to a file when the --json option is ' +
'also specified.',
type: 'string'
},
passWithNoTests: {
description:
'Will not fail if no tests are found (for example while using `--testPathPattern`.)',
type: 'boolean'
},
preset: {
description: "A preset that is used as a base for Jest's configuration.",
type: 'string'
},
prettierPath: {
description: 'The path to the "prettier" module used for inline snapshots.',
type: 'string'
},
projects: {
description:
'A list of projects that use Jest to run all tests of all ' +
'projects in a single instance of Jest.',
string: true,
type: 'array'
},
randomize: {
description:
'Shuffle the order of the tests within a file. In order to choose the seed refer to the `--seed` CLI option.',
type: 'boolean'
},
reporters: {
description: 'A list of custom reporters for the test suite.',
string: true,
type: 'array'
},
resetMocks: {
description:
'Automatically reset mock state before every test. ' +
'Equivalent to calling jest.resetAllMocks() before each test.',
type: 'boolean'
},
resetModules: {
description:
'If enabled, the module registry for every test file will ' +
'be reset before running each individual test.',
type: 'boolean'
},
resolver: {
description: 'A JSON string which allows the use of a custom resolver.',
type: 'string'
},
restoreMocks: {
description:
'Automatically restore mock state and implementation before every test. ' +
'Equivalent to calling jest.restoreAllMocks() before each test.',
type: 'boolean'
},
rootDir: {
description:
'The root directory that Jest should scan for tests and ' +
'modules within.',
type: 'string'
},
roots: {
description:
'A list of paths to directories that Jest should use to ' +
'search for files in.',
string: true,
type: 'array'
},
runInBand: {
alias: 'i',
description:
'Run all tests serially in the current process (rather than ' +
'creating a worker pool of child processes that run tests). This ' +
'is sometimes useful for debugging, but such use cases are pretty ' +
'rare.',
type: 'boolean'
},
runTestsByPath: {
description:
'Used when provided patterns are exact file paths. This avoids ' +
'converting them into a regular expression and matching it against ' +
'every single file.',
type: 'boolean'
},
runner: {
description:
"Allows to use a custom runner instead of Jest's default test runner.",
type: 'string'
},
seed: {
description:
'Sets a seed value that can be retrieved in a tests file via `jest.getSeed()`. If this option is not specified Jest will randomly generate the value. The seed value must be between `-0x80000000` and `0x7fffffff` inclusive.',
type: 'number'
},
selectProjects: {
description:
'Run the tests of the specified projects. ' +
'Jest uses the attribute `displayName` in the configuration to identify each project.',
string: true,
type: 'array'
},
setupFiles: {
description:
'A list of paths to modules that run some code to configure or ' +
'set up the testing environment before each test.',
string: true,
type: 'array'
},
setupFilesAfterEnv: {
description:
'A list of paths to modules that run some code to configure or ' +
'set up the testing framework before each test',
string: true,
type: 'array'
},
shard: {
description:
'Shard tests and execute only the selected shard, specify in ' +
'the form "current/all". 1-based, for example "3/5".',
type: 'string'
},
showConfig: {
description: 'Print your jest config and then exits.',
type: 'boolean'
},
showSeed: {
description:
'Prints the seed value in the test report summary. See `--seed` for how to set this value',
type: 'boolean'
},
silent: {
description: 'Prevent tests from printing messages through the console.',
type: 'boolean'
},
skipFilter: {
description:
'Disables the filter provided by --filter. Useful for CI jobs, or ' +
'local enforcement when fixing tests.',
type: 'boolean'
},
snapshotSerializers: {
description:
'A list of paths to snapshot serializer modules Jest should ' +
'use for snapshot testing.',
string: true,
type: 'array'
},
testEnvironment: {
description: 'Alias for --env',
type: 'string'
},
testEnvironmentOptions: {
description:
'A JSON string with options that will be passed to the `testEnvironment`. ' +
'The relevant options depend on the environment.',
type: 'string'
},
testFailureExitCode: {
description: 'Exit code of `jest` command if the test run failed',
type: 'string' // number
},
testLocationInResults: {
description: 'Add `location` information to the test results',
type: 'boolean'
},
testMatch: {
description: 'The glob patterns Jest uses to detect test files.',
string: true,
type: 'array'
},
testNamePattern: {
alias: 't',
description: 'Run only tests with a name that matches the regex pattern.',
type: 'string'
},
testPathIgnorePatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all test paths before executing the test. If the test path ' +
'matches any of the patterns, it will be skipped.',
string: true,
type: 'array'
},
testPathPattern: {
description:
'A regexp pattern string that is matched against all tests ' +
'paths before executing the test.',
string: true,
type: 'array'
},
testRegex: {
description:
'A string or array of string regexp patterns that Jest uses to detect test files.',
string: true,
type: 'array'
},
testResultsProcessor: {
description:
'Allows the use of a custom results processor. ' +
'This processor must be a node module that exports ' +
'a function expecting as the first argument the result object.',
type: 'string'
},
testRunner: {
description:
'Allows to specify a custom test runner. The default is' +
' `jest-circus/runner`. A path to a custom test runner can be provided:' +
' `<rootDir>/path/to/testRunner.js`.',
type: 'string'
},
testSequencer: {
description:
'Allows to specify a custom test sequencer. The default is ' +
'`@jest/test-sequencer`. A path to a custom test sequencer can be ' +
'provided: `<rootDir>/path/to/testSequencer.js`',
type: 'string'
},
testTimeout: {
description: 'This option sets the default timeouts of test cases.',
type: 'number'
},
transform: {
description:
'A JSON string which maps from regular expressions to paths ' +
'to transformers.',
type: 'string'
},
transformIgnorePatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all source file paths before transformation.',
string: true,
type: 'array'
},
unmockedModulePathPatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all modules before the module loader will automatically ' +
'return a mock for them.',
string: true,
type: 'array'
},
updateSnapshot: {
alias: 'u',
description:
'Use this flag to re-record snapshots. ' +
'Can be used together with a test suite pattern or with ' +
'`--testNamePattern` to re-record snapshot for test matching ' +
'the pattern',
type: 'boolean'
},
useStderr: {
description: 'Divert all output to stderr.',
type: 'boolean'
},
verbose: {
description:
'Display individual test results with the test suite hierarchy.',
type: 'boolean'
},
watch: {
description:
'Watch files for changes and rerun tests related to ' +
'changed files. If you want to re-run all tests when a file has ' +
'changed, use the `--watchAll` option.',
type: 'boolean'
},
watchAll: {
description:
'Watch files for changes and rerun all tests. If you want ' +
'to re-run only the tests related to the changed files, use the ' +
'`--watch` option.',
type: 'boolean'
},
watchPathIgnorePatterns: {
description:
'An array of regexp pattern strings that are matched ' +
'against all paths before trigger test re-run in watch mode. ' +
'If the test path matches any of the patterns, it will be skipped.',
string: true,
type: 'array'
},
watchman: {
description:
'Whether to use watchman for file crawling. Disable using ' +
'--no-watchman.',
type: 'boolean'
},
workerThreads: {
description:
'Whether to use worker threads for parallelization. Child processes ' +
'are used by default.',
type: 'boolean'
}
};
exports.options = options;

18
backend/node_modules/jest-cli/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,18 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Options} from 'yargs';
export declare function run(
maybeArgv?: Array<string>,
project?: string,
): Promise<void>;
export declare const yargsOptions: {
[key: string]: Options;
};
export {};

19
backend/node_modules/jest-cli/build/index.js generated vendored Normal file
View file

@ -0,0 +1,19 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'run', {
enumerable: true,
get: function () {
return _run.run;
}
});
Object.defineProperty(exports, 'yargsOptions', {
enumerable: true,
get: function () {
return _args.options;
}
});
var _run = require('./run');
var _args = require('./args');

239
backend/node_modules/jest-cli/build/run.js generated vendored Normal file
View file

@ -0,0 +1,239 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.buildArgv = buildArgv;
exports.run = run;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function _yargs() {
const data = _interopRequireDefault(require('yargs'));
_yargs = function () {
return data;
};
return data;
}
function _core() {
const data = require('@jest/core');
_core = function () {
return data;
};
return data;
}
function _createJest() {
const data = require('create-jest');
_createJest = function () {
return data;
};
return data;
}
function _jestConfig() {
const data = require('jest-config');
_jestConfig = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestValidate() {
const data = require('jest-validate');
_jestValidate = function () {
return data;
};
return data;
}
var args = _interopRequireWildcard(require('./args'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
async function run(maybeArgv, project) {
try {
const argv = await buildArgv(maybeArgv);
if (argv.init) {
await (0, _createJest().runCreate)();
return;
}
const projects = getProjectListFromCLIArgs(argv, project);
const {results, globalConfig} = await (0, _core().runCLI)(argv, projects);
readResultsAndExit(results, globalConfig);
} catch (error) {
(0, _jestUtil().clearLine)(process.stderr);
(0, _jestUtil().clearLine)(process.stdout);
if (error?.stack) {
console.error(_chalk().default.red(error.stack));
} else {
console.error(_chalk().default.red(error));
}
(0, _exit().default)(1);
throw error;
}
}
async function buildArgv(maybeArgv) {
const version =
(0, _core().getVersion)() +
(__dirname.includes(`packages${path().sep}jest-cli`) ? '-dev' : '');
const rawArgv = maybeArgv || process.argv.slice(2);
const argv = await (0, _yargs().default)(rawArgv)
.usage(args.usage)
.version(version)
.alias('help', 'h')
.options(args.options)
.epilogue(args.docs)
.check(args.check).argv;
(0, _jestValidate().validateCLIOptions)(
argv,
{
...args.options,
deprecationEntries: _jestConfig().deprecationEntries
},
// strip leading dashes
Array.isArray(rawArgv)
? rawArgv.map(rawArgv => rawArgv.replace(/^--?/, ''))
: Object.keys(rawArgv)
);
// strip dashed args
return Object.keys(argv).reduce(
(result, key) => {
if (!key.includes('-')) {
result[key] = argv[key];
}
return result;
},
{
$0: argv.$0,
_: argv._
}
);
}
const getProjectListFromCLIArgs = (argv, project) => {
const projects = argv.projects ? argv.projects : [];
if (project) {
projects.push(project);
}
if (!projects.length && process.platform === 'win32') {
try {
projects.push((0, _jestUtil().tryRealpath)(process.cwd()));
} catch {
// do nothing, just catch error
// process.binding('fs').realpath can throw, e.g. on mapped drives
}
}
if (!projects.length) {
projects.push(process.cwd());
}
return projects;
};
const readResultsAndExit = (result, globalConfig) => {
const code = !result || result.success ? 0 : globalConfig.testFailureExitCode;
// Only exit if needed
process.on('exit', () => {
if (typeof code === 'number' && code !== 0) {
process.exitCode = code;
}
});
if (globalConfig.forceExit) {
if (!globalConfig.detectOpenHandles) {
console.warn(
`${_chalk().default.bold(
'Force exiting Jest: '
)}Have you considered using \`--detectOpenHandles\` to detect ` +
'async operations that kept running after all tests finished?'
);
}
(0, _exit().default)(code);
} else if (
!globalConfig.detectOpenHandles &&
globalConfig.openHandlesTimeout !== 0
) {
const timeout = globalConfig.openHandlesTimeout;
setTimeout(() => {
console.warn(
_chalk().default.yellow.bold(
`Jest did not exit ${
timeout === 1000 ? 'one second' : `${timeout / 1000} seconds`
} after the test run has completed.\n\n'`
) +
_chalk().default.yellow(
'This usually means that there are asynchronous operations that ' +
"weren't stopped in your tests. Consider running Jest with " +
'`--detectOpenHandles` to troubleshoot this issue.'
)
);
}, timeout).unref();
}
};

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.

View file

@ -0,0 +1,3 @@
# `@jest/schemas`
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.

View file

@ -0,0 +1,63 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Static} from '@sinclair/typebox';
import {TBoolean} from '@sinclair/typebox';
import {TNull} from '@sinclair/typebox';
import {TNumber} from '@sinclair/typebox';
import {TObject} from '@sinclair/typebox';
import {TReadonlyOptional} from '@sinclair/typebox';
import {TString} from '@sinclair/typebox';
declare const RawSnapshotFormat: TObject<{
callToJSON: TReadonlyOptional<TBoolean>;
compareKeys: TReadonlyOptional<TNull>;
escapeRegex: TReadonlyOptional<TBoolean>;
escapeString: TReadonlyOptional<TBoolean>;
highlight: TReadonlyOptional<TBoolean>;
indent: TReadonlyOptional<TNumber>;
maxDepth: TReadonlyOptional<TNumber>;
maxWidth: TReadonlyOptional<TNumber>;
min: TReadonlyOptional<TBoolean>;
printBasicPrototype: TReadonlyOptional<TBoolean>;
printFunctionName: TReadonlyOptional<TBoolean>;
theme: TReadonlyOptional<
TObject<{
comment: TReadonlyOptional<TString<string>>;
content: TReadonlyOptional<TString<string>>;
prop: TReadonlyOptional<TString<string>>;
tag: TReadonlyOptional<TString<string>>;
value: TReadonlyOptional<TString<string>>;
}>
>;
}>;
export declare const SnapshotFormat: TObject<{
callToJSON: TReadonlyOptional<TBoolean>;
compareKeys: TReadonlyOptional<TNull>;
escapeRegex: TReadonlyOptional<TBoolean>;
escapeString: TReadonlyOptional<TBoolean>;
highlight: TReadonlyOptional<TBoolean>;
indent: TReadonlyOptional<TNumber>;
maxDepth: TReadonlyOptional<TNumber>;
maxWidth: TReadonlyOptional<TNumber>;
min: TReadonlyOptional<TBoolean>;
printBasicPrototype: TReadonlyOptional<TBoolean>;
printFunctionName: TReadonlyOptional<TBoolean>;
theme: TReadonlyOptional<
TObject<{
comment: TReadonlyOptional<TString<string>>;
content: TReadonlyOptional<TString<string>>;
prop: TReadonlyOptional<TString<string>>;
tag: TReadonlyOptional<TString<string>>;
value: TReadonlyOptional<TString<string>>;
}>
>;
}>;
export declare type SnapshotFormat = Static<typeof RawSnapshotFormat>;
export {};

View file

@ -0,0 +1,60 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.SnapshotFormat = void 0;
function _typebox() {
const data = require('@sinclair/typebox');
_typebox = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const RawSnapshotFormat = _typebox().Type.Partial(
_typebox().Type.Object({
callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()),
compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()),
escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()),
escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()),
highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()),
indent: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
maxDepth: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
maxWidth: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
min: _typebox().Type.Readonly(_typebox().Type.Boolean()),
printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()),
printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()),
theme: _typebox().Type.Readonly(
_typebox().Type.Partial(
_typebox().Type.Object({
comment: _typebox().Type.Readonly(_typebox().Type.String()),
content: _typebox().Type.Readonly(_typebox().Type.String()),
prop: _typebox().Type.Readonly(_typebox().Type.String()),
tag: _typebox().Type.Readonly(_typebox().Type.String()),
value: _typebox().Type.Readonly(_typebox().Type.String())
})
)
)
})
);
const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat);
exports.SnapshotFormat = SnapshotFormat;

View file

@ -0,0 +1,29 @@
{
"name": "@jest/schemas",
"version": "29.6.3",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-schemas"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@sinclair/typebox": "^0.27.8"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
}

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.

View file

@ -0,0 +1,30 @@
# @jest/types
This package contains shared types of Jest's packages.
If you are looking for types of [Jest globals](https://jestjs.io/docs/api), you can import them from `@jest/globals` package:
```ts
import {describe, expect, it} from '@jest/globals';
describe('my tests', () => {
it('works', () => {
expect(1).toBe(1);
});
});
```
If you prefer to omit imports, a similar result can be achieved installing the [@types/jest](https://npmjs.com/package/@types/jest) package. Note that this is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) and may not cover the latest Jest features.
Another use-case for `@types/jest` is a typed Jest config as those types are not provided by Jest out of the box:
```ts
// jest.config.ts
import {Config} from '@jest/types';
const config: Config.InitialOptions = {
// some typed config
};
export default config;
```

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1 @@
'use strict';

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,38 @@
{
"name": "@jest/types",
"version": "29.6.3",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-types"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/schemas": "^29.6.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^17.0.8",
"chalk": "^4.0.0"
},
"devDependencies": {
"@tsd/typescript": "^5.0.4",
"tsd-lite": "^0.7.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
}

View file

@ -0,0 +1,35 @@
import * as Types from '../typebox';
import { ValueErrorIterator } from '../errors/index';
export type CheckFunction = (value: unknown) => boolean;
export declare class TypeCheck<T extends Types.TSchema> {
private readonly schema;
private readonly references;
private readonly checkFunc;
private readonly code;
constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated assertion code used to validate this type. */
Code(): string;
/** Returns an iterator for each error in this value. */
Errors(value: unknown): ValueErrorIterator;
/** Returns true if the value matches the compiled type. */
Check(value: unknown): value is Types.Static<T>;
}
export declare class TypeCompilerUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class TypeCompilerDereferenceError extends Error {
readonly schema: Types.TRef;
constructor(schema: Types.TRef);
}
export declare class TypeCompilerTypeGuardError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** Returns the generated assertion code used to validate this type. */
function Code<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): string;
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
}

View file

@ -0,0 +1,577 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeCompiler = exports.TypeCompilerTypeGuardError = exports.TypeCompilerDereferenceError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
const Types = require("../typebox");
const index_1 = require("../errors/index");
const index_2 = require("../system/index");
const hash_1 = require("../value/hash");
// -------------------------------------------------------------------
// TypeCheck
// -------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
}
/** Returns the generated assertion code used to validate this type. */
Code() {
return this.code;
}
/** Returns an iterator for each error in this value. */
Errors(value) {
return index_1.ValueErrors.Errors(this.schema, this.references, value);
}
/** Returns true if the value matches the compiled type. */
Check(value) {
return this.checkFunc(value);
}
}
exports.TypeCheck = TypeCheck;
// -------------------------------------------------------------------
// Character
// -------------------------------------------------------------------
var Character;
(function (Character) {
function DollarSign(code) {
return code === 36;
}
Character.DollarSign = DollarSign;
function IsUnderscore(code) {
return code === 95;
}
Character.IsUnderscore = IsUnderscore;
function IsAlpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
Character.IsAlpha = IsAlpha;
function IsNumeric(code) {
return code >= 48 && code <= 57;
}
Character.IsNumeric = IsNumeric;
})(Character || (Character = {}));
// -------------------------------------------------------------------
// MemberExpression
// -------------------------------------------------------------------
var MemberExpression;
(function (MemberExpression) {
function IsFirstCharacterNumeric(value) {
if (value.length === 0)
return false;
return Character.IsNumeric(value.charCodeAt(0));
}
function IsAccessor(value) {
if (IsFirstCharacterNumeric(value))
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code);
if (!check)
return false;
}
return true;
}
function EscapeHyphen(key) {
return key.replace(/'/g, "\\'");
}
function Encode(object, key) {
return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`;
}
MemberExpression.Encode = Encode;
})(MemberExpression || (MemberExpression = {}));
// -------------------------------------------------------------------
// Identifier
// -------------------------------------------------------------------
var Identifier;
(function (Identifier) {
function Encode($id) {
const buffer = [];
for (let i = 0; i < $id.length; i++) {
const code = $id.charCodeAt(i);
if (Character.IsNumeric(code) || Character.IsAlpha(code)) {
buffer.push($id.charAt(i));
}
else {
buffer.push(`_${code}_`);
}
}
return buffer.join('').replace(/__/g, '_');
}
Identifier.Encode = Encode;
})(Identifier || (Identifier = {}));
// -------------------------------------------------------------------
// TypeCompiler
// -------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends Error {
constructor(schema) {
super('TypeCompiler: Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
class TypeCompilerDereferenceError extends Error {
constructor(schema) {
super(`TypeCompiler: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.TypeCompilerDereferenceError = TypeCompilerDereferenceError;
class TypeCompilerTypeGuardError extends Error {
constructor(schema) {
super('TypeCompiler: Preflight validation check failed to guard for the given schema');
this.schema = schema;
}
}
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// -------------------------------------------------------------------
// Guards
// -------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsNumber(value) {
return typeof value === 'number' && globalThis.Number.isFinite(value);
}
function IsString(value) {
return typeof value === 'string';
}
// -------------------------------------------------------------------
// Polices
// -------------------------------------------------------------------
function IsExactOptionalProperty(value, key, expression) {
return index_2.TypeSystem.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
}
function IsObjectCheck(value) {
return !index_2.TypeSystem.AllowArrayObjects ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
}
function IsRecordCheck(value) {
return !index_2.TypeSystem.AllowArrayObjects
? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`
: `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`;
}
function IsNumberCheck(value) {
return !index_2.TypeSystem.AllowNaN ? `(typeof ${value} === 'number' && Number.isFinite(${value}))` : `typeof ${value} === 'number'`;
}
function IsVoidCheck(value) {
return index_2.TypeSystem.AllowVoidNull ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
}
// -------------------------------------------------------------------
// Types
// -------------------------------------------------------------------
function* Any(schema, references, value) {
yield 'true';
}
function* Array(schema, references, value) {
const expression = CreateExpression(schema.items, references, 'value');
yield `Array.isArray(${value}) && ${value}.every(value => ${expression})`;
if (IsNumber(schema.minItems))
yield `${value}.length >= ${schema.minItems}`;
if (IsNumber(schema.maxItems))
yield `${value}.length <= ${schema.maxItems}`;
if (schema.uniqueItems === true)
yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
}
function* BigInt(schema, references, value) {
yield `(typeof ${value} === 'bigint')`;
if (IsBigInt(schema.multipleOf))
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
if (IsBigInt(schema.exclusiveMinimum))
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
if (IsBigInt(schema.exclusiveMaximum))
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
if (IsBigInt(schema.minimum))
yield `${value} >= BigInt(${schema.minimum})`;
if (IsBigInt(schema.maximum))
yield `${value} <= BigInt(${schema.maximum})`;
}
function* Boolean(schema, references, value) {
yield `typeof ${value} === 'boolean'`;
}
function* Constructor(schema, references, value) {
yield* Visit(schema.returns, references, `${value}.prototype`);
}
function* Date(schema, references, value) {
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
if (IsNumber(schema.exclusiveMinimumTimestamp))
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
if (IsNumber(schema.exclusiveMaximumTimestamp))
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
if (IsNumber(schema.minimumTimestamp))
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
if (IsNumber(schema.maximumTimestamp))
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
}
function* Function(schema, references, value) {
yield `typeof ${value} === 'function'`;
}
function* Integer(schema, references, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (IsNumber(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
if (IsNumber(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if (IsNumber(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if (IsNumber(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if (IsNumber(schema.maximum))
yield `${value} <= ${schema.maximum}`;
}
function* Intersect(schema, references, value) {
if (schema.unevaluatedProperties === undefined) {
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
yield `${expressions.join(' && ')}`;
}
else if (schema.unevaluatedProperties === false) {
// prettier-ignore
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
const expression1 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key))`;
yield `${expressions.join(' && ')} && ${expression1}`;
}
else if (typeof schema.unevaluatedProperties === 'object') {
// prettier-ignore
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
const expression1 = CreateExpression(schema.unevaluatedProperties, references, 'value[key]');
const expression2 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key) || ${expression1})`;
yield `${expressions.join(' && ')} && ${expression2}`;
}
}
function* Literal(schema, references, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `${value} === ${schema.const}`;
}
else {
yield `${value} === '${schema.const}'`;
}
}
function* Never(schema, references, value) {
yield `false`;
}
function* Not(schema, references, value) {
const left = CreateExpression(schema.allOf[0].not, references, value);
const right = CreateExpression(schema.allOf[1], references, value);
yield `!${left} && ${right}`;
}
function* Null(schema, references, value) {
yield `${value} === null`;
}
function* Number(schema, references, value) {
yield IsNumberCheck(value);
if (IsNumber(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
if (IsNumber(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if (IsNumber(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if (IsNumber(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if (IsNumber(schema.maximum))
yield `${value} <= ${schema.maximum}`;
}
function* Object(schema, references, value) {
yield IsObjectCheck(value);
if (IsNumber(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if (IsNumber(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
for (const knownKey of knownKeys) {
const memberExpression = MemberExpression.Encode(value, knownKey);
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, memberExpression);
if (Types.ExtendsUndefined.Check(property))
yield `('${knownKey}' in ${value})`;
}
else {
const expression = CreateExpression(property, references, memberExpression);
yield IsExactOptionalProperty(value, knownKey, expression);
}
}
if (schema.additionalProperties === false) {
if (schema.required && schema.required.length === knownKeys.length) {
yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`;
}
else {
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`;
}
}
if (typeof schema.additionalProperties === 'object') {
const expression = CreateExpression(schema.additionalProperties, references, 'value[key]');
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
}
}
function* Promise(schema, references, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
}
function* Record(schema, references, value) {
yield IsRecordCheck(value);
if (IsNumber(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if (IsNumber(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
const expression = CreateExpression(valueSchema, references, 'value');
yield `Object.values(${value}).every(value => ${expression})`;
}
function* Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new TypeCompilerDereferenceError(schema);
const target = references[index];
// Reference: If we have seen this reference before we can just yield and return
// the function call. If this isn't the case we defer to visit to generate and
// set the function for subsequent passes. Consider for refactor.
if (state_local_function_names.has(schema.$ref))
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
yield* Visit(target, references, value);
}
function* String(schema, references, value) {
yield `(typeof ${value} === 'string')`;
if (IsNumber(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
if (IsNumber(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if (schema.pattern !== undefined) {
const local = PushLocal(`${new RegExp(schema.pattern)};`);
yield `${local}.test(${value})`;
}
if (schema.format !== undefined) {
yield `format('${schema.format}', ${value})`;
}
}
function* Symbol(schema, references, value) {
yield `(typeof ${value} === 'symbol')`;
}
function* TemplateLiteral(schema, references, value) {
yield `(typeof ${value} === 'string')`;
const local = PushLocal(`${new RegExp(schema.pattern)};`);
yield `${local}.test(${value})`;
}
function* This(schema, references, value) {
const func = CreateFunctionName(schema.$ref);
yield `${func}(${value})`;
}
function* Tuple(schema, references, value) {
yield `(Array.isArray(${value}))`;
if (schema.items === undefined)
return yield `${value}.length === 0`;
yield `(${value}.length === ${schema.maxItems})`;
for (let i = 0; i < schema.items.length; i++) {
const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`);
yield `${expression}`;
}
}
function* Undefined(schema, references, value) {
yield `${value} === undefined`;
}
function* Union(schema, references, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
yield `(${expressions.join(' || ')})`;
}
function* Uint8Array(schema, references, value) {
yield `${value} instanceof Uint8Array`;
if (IsNumber(schema.maxByteLength))
yield `(${value}.length <= ${schema.maxByteLength})`;
if (IsNumber(schema.minByteLength))
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* Unknown(schema, references, value) {
yield 'true';
}
function* Void(schema, references, value) {
yield IsVoidCheck(value);
}
function* UserDefined(schema, references, value) {
const schema_key = `schema_key_${state_remote_custom_types.size}`;
state_remote_custom_types.set(schema_key, schema);
yield `custom('${schema[Types.Kind]}', '${schema_key}', ${value})`;
}
function* Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
// Reference: Referenced schemas can originate from either additional schemas
// or inline in the schema itself. Ideally the recursive path should align to
// reference path. Consider for refactor.
if (IsString(schema.$id) && !state_local_function_names.has(schema.$id)) {
state_local_function_names.add(schema.$id);
const name = CreateFunctionName(schema.$id);
const body = CreateFunction(name, schema, references, 'value');
PushFunction(body);
yield `${name}(${value})`;
return;
}
switch (schema_[Types.Kind]) {
case 'Any':
return yield* Any(schema_, references_, value);
case 'Array':
return yield* Array(schema_, references_, value);
case 'BigInt':
return yield* BigInt(schema_, references_, value);
case 'Boolean':
return yield* Boolean(schema_, references_, value);
case 'Constructor':
return yield* Constructor(schema_, references_, value);
case 'Date':
return yield* Date(schema_, references_, value);
case 'Function':
return yield* Function(schema_, references_, value);
case 'Integer':
return yield* Integer(schema_, references_, value);
case 'Intersect':
return yield* Intersect(schema_, references_, value);
case 'Literal':
return yield* Literal(schema_, references_, value);
case 'Never':
return yield* Never(schema_, references_, value);
case 'Not':
return yield* Not(schema_, references_, value);
case 'Null':
return yield* Null(schema_, references_, value);
case 'Number':
return yield* Number(schema_, references_, value);
case 'Object':
return yield* Object(schema_, references_, value);
case 'Promise':
return yield* Promise(schema_, references_, value);
case 'Record':
return yield* Record(schema_, references_, value);
case 'Ref':
return yield* Ref(schema_, references_, value);
case 'String':
return yield* String(schema_, references_, value);
case 'Symbol':
return yield* Symbol(schema_, references_, value);
case 'TemplateLiteral':
return yield* TemplateLiteral(schema_, references_, value);
case 'This':
return yield* This(schema_, references_, value);
case 'Tuple':
return yield* Tuple(schema_, references_, value);
case 'Undefined':
return yield* Undefined(schema_, references_, value);
case 'Union':
return yield* Union(schema_, references_, value);
case 'Uint8Array':
return yield* Uint8Array(schema_, references_, value);
case 'Unknown':
return yield* Unknown(schema_, references_, value);
case 'Void':
return yield* Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new TypeCompilerUnknownTypeError(schema);
return yield* UserDefined(schema_, references_, value);
}
}
// -------------------------------------------------------------------
// Compiler State
// -------------------------------------------------------------------
const state_local_variables = new Set(); // local variables and functions
const state_local_function_names = new Set(); // local function names used call ref validators
const state_remote_custom_types = new Map(); // remote custom types used during compilation
function ResetCompiler() {
state_local_variables.clear();
state_local_function_names.clear();
state_remote_custom_types.clear();
}
function CreateExpression(schema, references, value) {
return `(${[...Visit(schema, references, value)].join(' && ')})`;
}
function CreateFunctionName($id) {
return `check_${Identifier.Encode($id)}`;
}
function CreateFunction(name, schema, references, value) {
const expression = [...Visit(schema, references, value)].map((condition) => ` ${condition}`).join(' &&\n');
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
}
function PushFunction(functionBody) {
state_local_variables.add(functionBody);
}
function PushLocal(expression) {
const local = `local_${state_local_variables.size}`;
state_local_variables.add(`const ${local} = ${expression}`);
return local;
}
function GetLocals() {
return [...state_local_variables.values()];
}
// -------------------------------------------------------------------
// Compile
// -------------------------------------------------------------------
function Build(schema, references) {
ResetCompiler();
const check = CreateFunction('check', schema, references, 'value');
const locals = GetLocals();
return `${locals.join('\n')}\nreturn ${check}`;
}
/** Returns the generated assertion code used to validate this type. */
function Code(schema, references = []) {
if (!Types.TypeGuard.TSchema(schema))
throw new TypeCompilerTypeGuardError(schema);
for (const schema of references)
if (!Types.TypeGuard.TSchema(schema))
throw new TypeCompilerTypeGuardError(schema);
return Build(schema, references);
}
TypeCompiler.Code = Code;
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, references = []) {
const code = Code(schema, references);
const custom_schemas = new Map(state_remote_custom_types);
const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
const checkFunction = compiledFunction((kind, schema_key, value) => {
if (!Types.TypeRegistry.Has(kind) || !custom_schemas.has(schema_key))
return false;
const schema = custom_schemas.get(schema_key);
const func = Types.TypeRegistry.Get(kind);
return func(schema, value);
}, (format, value) => {
if (!Types.FormatRegistry.Has(format))
return false;
const func = Types.FormatRegistry.Get(format);
return func(value);
}, (value) => {
return hash_1.ValueHash.Create(value);
});
return new TypeCheck(schema, references, checkFunction, code);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));

View file

@ -0,0 +1,2 @@
export { ValueError, ValueErrorType } from '../errors/index';
export * from './compiler';

View file

@ -0,0 +1,47 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorType = void 0;
var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
__exportStar(require("./compiler"), exports);

View file

@ -0,0 +1,88 @@
import * as Types from '../typebox';
export declare enum ValueErrorType {
Array = 0,
ArrayMinItems = 1,
ArrayMaxItems = 2,
ArrayUniqueItems = 3,
BigInt = 4,
BigIntMultipleOf = 5,
BigIntExclusiveMinimum = 6,
BigIntExclusiveMaximum = 7,
BigIntMinimum = 8,
BigIntMaximum = 9,
Boolean = 10,
Date = 11,
DateExclusiveMinimumTimestamp = 12,
DateExclusiveMaximumTimestamp = 13,
DateMinimumTimestamp = 14,
DateMaximumTimestamp = 15,
Function = 16,
Integer = 17,
IntegerMultipleOf = 18,
IntegerExclusiveMinimum = 19,
IntegerExclusiveMaximum = 20,
IntegerMinimum = 21,
IntegerMaximum = 22,
Intersect = 23,
IntersectUnevaluatedProperties = 24,
Literal = 25,
Never = 26,
Not = 27,
Null = 28,
Number = 29,
NumberMultipleOf = 30,
NumberExclusiveMinimum = 31,
NumberExclusiveMaximum = 32,
NumberMinumum = 33,
NumberMaximum = 34,
Object = 35,
ObjectMinProperties = 36,
ObjectMaxProperties = 37,
ObjectAdditionalProperties = 38,
ObjectRequiredProperties = 39,
Promise = 40,
RecordKeyNumeric = 41,
RecordKeyString = 42,
String = 43,
StringMinLength = 44,
StringMaxLength = 45,
StringPattern = 46,
StringFormatUnknown = 47,
StringFormat = 48,
Symbol = 49,
TupleZeroLength = 50,
TupleLength = 51,
Undefined = 52,
Union = 53,
Uint8Array = 54,
Uint8ArrayMinByteLength = 55,
Uint8ArrayMaxByteLength = 56,
Void = 57,
Custom = 58
}
export interface ValueError {
type: ValueErrorType;
schema: Types.TSchema;
path: string;
value: unknown;
message: string;
}
export declare class ValueErrorIterator {
private readonly iterator;
constructor(iterator: IterableIterator<ValueError>);
[Symbol.iterator](): IterableIterator<ValueError>;
/** Returns the first value error or undefined if no errors */
First(): ValueError | undefined;
}
export declare class ValueErrorsUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueErrorsDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
export declare namespace ValueErrors {
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): ValueErrorIterator;
}

View file

@ -0,0 +1,609 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrors = exports.ValueErrorsDereferenceError = exports.ValueErrorsUnknownTypeError = exports.ValueErrorIterator = exports.ValueErrorType = void 0;
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
const Types = require("../typebox");
const index_1 = require("../system/index");
const hash_1 = require("../value/hash");
// -------------------------------------------------------------------
// ValueErrorType
// -------------------------------------------------------------------
var ValueErrorType;
(function (ValueErrorType) {
ValueErrorType[ValueErrorType["Array"] = 0] = "Array";
ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems";
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems";
ValueErrorType[ValueErrorType["BigInt"] = 4] = "BigInt";
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 5] = "BigIntMultipleOf";
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 6] = "BigIntExclusiveMinimum";
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 7] = "BigIntExclusiveMaximum";
ValueErrorType[ValueErrorType["BigIntMinimum"] = 8] = "BigIntMinimum";
ValueErrorType[ValueErrorType["BigIntMaximum"] = 9] = "BigIntMaximum";
ValueErrorType[ValueErrorType["Boolean"] = 10] = "Boolean";
ValueErrorType[ValueErrorType["Date"] = 11] = "Date";
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 12] = "DateExclusiveMinimumTimestamp";
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 13] = "DateExclusiveMaximumTimestamp";
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 14] = "DateMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 15] = "DateMaximumTimestamp";
ValueErrorType[ValueErrorType["Function"] = 16] = "Function";
ValueErrorType[ValueErrorType["Integer"] = 17] = "Integer";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 18] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 19] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 20] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 21] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 22] = "IntegerMaximum";
ValueErrorType[ValueErrorType["Intersect"] = 23] = "Intersect";
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 24] = "IntersectUnevaluatedProperties";
ValueErrorType[ValueErrorType["Literal"] = 25] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 26] = "Never";
ValueErrorType[ValueErrorType["Not"] = 27] = "Not";
ValueErrorType[ValueErrorType["Null"] = 28] = "Null";
ValueErrorType[ValueErrorType["Number"] = 29] = "Number";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 30] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 31] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 32] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberMinumum"] = 33] = "NumberMinumum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 34] = "NumberMaximum";
ValueErrorType[ValueErrorType["Object"] = 35] = "Object";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 36] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 37] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 38] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 39] = "ObjectRequiredProperties";
ValueErrorType[ValueErrorType["Promise"] = 40] = "Promise";
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 41] = "RecordKeyNumeric";
ValueErrorType[ValueErrorType["RecordKeyString"] = 42] = "RecordKeyString";
ValueErrorType[ValueErrorType["String"] = 43] = "String";
ValueErrorType[ValueErrorType["StringMinLength"] = 44] = "StringMinLength";
ValueErrorType[ValueErrorType["StringMaxLength"] = 45] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringPattern"] = 46] = "StringPattern";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 47] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 48] = "StringFormat";
ValueErrorType[ValueErrorType["Symbol"] = 49] = "Symbol";
ValueErrorType[ValueErrorType["TupleZeroLength"] = 50] = "TupleZeroLength";
ValueErrorType[ValueErrorType["TupleLength"] = 51] = "TupleLength";
ValueErrorType[ValueErrorType["Undefined"] = 52] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 53] = "Union";
ValueErrorType[ValueErrorType["Uint8Array"] = 54] = "Uint8Array";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 55] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 56] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Void"] = 57] = "Void";
ValueErrorType[ValueErrorType["Custom"] = 58] = "Custom";
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
// -------------------------------------------------------------------
// ValueErrorIterator
// -------------------------------------------------------------------
class ValueErrorIterator {
constructor(iterator) {
this.iterator = iterator;
}
[Symbol.iterator]() {
return this.iterator;
}
/** Returns the first value error or undefined if no errors */
First() {
const next = this.iterator.next();
return next.done ? undefined : next.value;
}
}
exports.ValueErrorIterator = ValueErrorIterator;
// -------------------------------------------------------------------
// ValueErrors
// -------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends Error {
constructor(schema) {
super('ValueErrors: Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
class ValueErrorsDereferenceError extends Error {
constructor(schema) {
super(`ValueErrors: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueErrorsDereferenceError = ValueErrorsDereferenceError;
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
var ValueErrors;
(function (ValueErrors) {
// ----------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsInteger(value) {
return globalThis.Number.isInteger(value);
}
function IsString(value) {
return typeof value === 'string';
}
function IsDefined(value) {
return value !== undefined;
}
// ----------------------------------------------------------------------
// Policies
// ----------------------------------------------------------------------
function IsExactOptionalProperty(value, key) {
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
}
function IsObject(value) {
const result = typeof value === 'object' && value !== null;
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
}
function IsRecordObject(value) {
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
}
function IsNumber(value) {
const result = typeof value === 'number';
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
}
function IsVoid(value) {
const result = value === undefined;
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
function* Any(schema, references, path, value) { }
function* Array(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` };
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = hash_1.ValueHash.Create(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` };
}
for (let i = 0; i < value.length; i++) {
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
}
}
function* BigInt(schema, references, path, value) {
if (!IsBigInt(value)) {
return yield { type: ValueErrorType.BigInt, schema, path, value, message: `Expected bigint` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
yield { type: ValueErrorType.BigIntMultipleOf, schema, path, value, message: `Expected bigint to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.BigIntExclusiveMinimum, schema, path, value, message: `Expected bigint to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.BigIntExclusiveMaximum, schema, path, value, message: `Expected bigint to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.BigIntMinimum, schema, path, value, message: `Expected bigint to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.BigIntMaximum, schema, path, value, message: `Expected bigint to be less or equal to ${schema.maximum}` };
}
}
function* Boolean(schema, references, path, value) {
if (!(typeof value === 'boolean')) {
return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` };
}
}
function* Constructor(schema, references, path, value) {
yield* Visit(schema.returns, references, path, value.prototype);
}
function* Date(schema, references, path, value) {
if (!(value instanceof globalThis.Date)) {
return yield { type: ValueErrorType.Date, schema, path, value, message: `Expected Date object` };
}
if (!globalThis.isFinite(value.getTime())) {
return yield { type: ValueErrorType.Date, schema, path, value, message: `Invalid Date` };
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
yield { type: ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
yield { type: ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
yield { type: ValueErrorType.DateMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
yield { type: ValueErrorType.DateMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less or equal to ${schema.maximum}` };
}
}
function* Function(schema, references, path, value) {
if (!(typeof value === 'function')) {
return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` };
}
}
function* Integer(schema, references, path, value) {
if (!IsInteger(value)) {
return yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
}
}
function* Intersect(schema, references, path, value) {
for (const subschema of schema.allOf) {
const next = Visit(subschema, references, path, value).next();
if (!next.done) {
yield next.value;
yield { type: ValueErrorType.Intersect, schema, path, value, message: `Expected all sub schemas to be valid` };
return;
}
}
if (schema.unevaluatedProperties === false) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
for (const valueKey of valueKeys) {
if (!schemaKeys.includes(valueKey)) {
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Unexpected property` };
}
}
}
if (typeof schema.unevaluatedProperties === 'object') {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
for (const valueKey of valueKeys) {
if (!schemaKeys.includes(valueKey)) {
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
if (!next.done) {
yield next.value;
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Invalid additional property` };
return;
}
}
}
}
}
function* Literal(schema, references, path, value) {
if (!(value === schema.const)) {
const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const;
return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` };
}
}
function* Never(schema, references, path, value) {
yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` };
}
function* Not(schema, references, path, value) {
if (Visit(schema.allOf[0].not, references, path, value).next().done === true) {
yield { type: ValueErrorType.Not, schema, path, value, message: `Value should not validate` };
}
yield* Visit(schema.allOf[1], references, path, value);
}
function* Null(schema, references, path, value) {
if (!(value === null)) {
return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` };
}
}
function* Number(schema, references, path, value) {
if (!IsNumber(value)) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` };
}
}
function* Object(schema, references, path, value) {
if (!IsObject(value)) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const requiredKeys = globalThis.Array.isArray(schema.required) ? schema.required : [];
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
const unknownKeys = globalThis.Object.getOwnPropertyNames(value);
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
if (Types.ExtendsUndefined.Check(schema) && !(knownKey in value)) {
yield { type: ValueErrorType.ObjectRequiredProperties, schema: property, path: `${path}/${knownKey}`, value: undefined, message: `Expected required property` };
}
}
else {
if (IsExactOptionalProperty(value, knownKey)) {
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
}
}
}
for (const requiredKey of requiredKeys) {
if (unknownKeys.includes(requiredKey))
continue;
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
}
if (schema.additionalProperties === false) {
for (const valueKey of unknownKeys) {
if (!knownKeys.includes(valueKey)) {
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${valueKey}`, value: value[valueKey], message: `Unexpected property` };
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const valueKey of unknownKeys) {
if (knownKeys.includes(valueKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${valueKey}`, value[valueKey]);
}
}
}
function* Promise(schema, references, path, value) {
if (!(typeof value === 'object' && typeof value.then === 'function')) {
yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` };
}
}
function* Record(schema, references, path, value) {
if (!IsRecordObject(value)) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected record object` };
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
const numeric = keyPattern === Types.PatternNumberExact;
const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString;
const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings';
return yield { type, schema, path, value, message };
}
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue);
}
}
function* Ref(schema, references, path, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueErrorsDereferenceError(schema);
const target = references[index];
yield* Visit(target, references, path, value);
}
function* String(schema, references, path, value) {
if (!IsString(value)) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` };
}
if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
}
}
if (schema.format !== undefined) {
if (!Types.FormatRegistry.Has(schema.format)) {
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
}
else {
const format = Types.FormatRegistry.Get(schema.format);
if (!format(value)) {
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
}
}
}
}
function* Symbol(schema, references, path, value) {
if (!(typeof value === 'symbol')) {
return yield { type: ValueErrorType.Symbol, schema, path, value, message: 'Expected symbol' };
}
}
function* TemplateLiteral(schema, references, path, value) {
if (!IsString(value)) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
}
}
function* This(schema, references, path, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueErrorsDereferenceError(schema);
const target = references[index];
yield* Visit(target, references, path, value);
}
function* Tuple(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' };
}
if (schema.items === undefined && !(value.length === 0)) {
return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' };
}
if (!(value.length === schema.maxItems)) {
yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` };
}
if (!schema.items) {
return;
}
for (let i = 0; i < schema.items.length; i++) {
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
}
}
function* Undefined(schema, references, path, value) {
if (!(value === undefined)) {
yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` };
}
}
function* Union(schema, references, path, value) {
const errors = [];
for (const inner of schema.anyOf) {
const variantErrors = [...Visit(inner, references, path, value)];
if (variantErrors.length === 0)
return;
errors.push(...variantErrors);
}
if (errors.length > 0) {
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
}
for (const error of errors) {
yield error;
}
}
function* Uint8Array(schema, references, path, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
}
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` };
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` };
}
}
function* Unknown(schema, references, path, value) { }
function* Void(schema, references, path, value) {
if (!IsVoid(value)) {
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected void` };
}
}
function* UserDefined(schema, references, path, value) {
const check = Types.TypeRegistry.Get(schema[Types.Kind]);
if (!check(schema, value)) {
return yield { type: ValueErrorType.Custom, schema, path, value, message: `Expected kind ${schema[Types.Kind]}` };
}
}
function* Visit(schema, references, path, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return yield* Any(schema_, references_, path, value);
case 'Array':
return yield* Array(schema_, references_, path, value);
case 'BigInt':
return yield* BigInt(schema_, references_, path, value);
case 'Boolean':
return yield* Boolean(schema_, references_, path, value);
case 'Constructor':
return yield* Constructor(schema_, references_, path, value);
case 'Date':
return yield* Date(schema_, references_, path, value);
case 'Function':
return yield* Function(schema_, references_, path, value);
case 'Integer':
return yield* Integer(schema_, references_, path, value);
case 'Intersect':
return yield* Intersect(schema_, references_, path, value);
case 'Literal':
return yield* Literal(schema_, references_, path, value);
case 'Never':
return yield* Never(schema_, references_, path, value);
case 'Not':
return yield* Not(schema_, references_, path, value);
case 'Null':
return yield* Null(schema_, references_, path, value);
case 'Number':
return yield* Number(schema_, references_, path, value);
case 'Object':
return yield* Object(schema_, references_, path, value);
case 'Promise':
return yield* Promise(schema_, references_, path, value);
case 'Record':
return yield* Record(schema_, references_, path, value);
case 'Ref':
return yield* Ref(schema_, references_, path, value);
case 'String':
return yield* String(schema_, references_, path, value);
case 'Symbol':
return yield* Symbol(schema_, references_, path, value);
case 'TemplateLiteral':
return yield* TemplateLiteral(schema_, references_, path, value);
case 'This':
return yield* This(schema_, references_, path, value);
case 'Tuple':
return yield* Tuple(schema_, references_, path, value);
case 'Undefined':
return yield* Undefined(schema_, references_, path, value);
case 'Union':
return yield* Union(schema_, references_, path, value);
case 'Uint8Array':
return yield* Uint8Array(schema_, references_, path, value);
case 'Unknown':
return yield* Unknown(schema_, references_, path, value);
case 'Void':
return yield* Void(schema_, references_, path, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueErrorsUnknownTypeError(schema);
return yield* UserDefined(schema_, references_, path, value);
}
}
function Errors(schema, references, value) {
const iterator = Visit(schema, references, '', value);
return new ValueErrorIterator(iterator);
}
ValueErrors.Errors = Errors;
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));

View file

@ -0,0 +1 @@
export * from './errors';

View file

@ -0,0 +1,44 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./errors"), exports);

View file

@ -0,0 +1,23 @@
TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.

View file

@ -0,0 +1,49 @@
{
"name": "@sinclair/typebox",
"version": "0.27.10",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
"keywords": [
"typescript",
"json-schema",
"validate",
"typecheck"
],
"author": "sinclairzx81",
"license": "MIT",
"main": "./typebox.js",
"types": "./typebox.d.ts",
"exports": {
"./compiler": "./compiler/index.js",
"./errors": "./errors/index.js",
"./system": "./system/index.js",
"./value": "./value/index.js",
".": "./typebox.js"
},
"repository": {
"type": "git",
"url": "https://github.com/sinclairzx81/typebox-legacy"
},
"scripts": {
"clean": "hammer task clean",
"format": "hammer task format",
"start": "hammer task start",
"test": "hammer task test",
"benchmark": "hammer task benchmark",
"build": "hammer task build",
"build:native": "hammer task build_native",
"publish": "hammer task publish"
},
"devDependencies": {
"@sinclair/hammer": "^0.17.1",
"@typescript/native-preview": "^7.0.0-dev.20260203.1",
"@types/chai": "^4.3.3",
"@types/mocha": "^9.1.1",
"@types/node": "^18.19.130",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"chai": "^4.3.6",
"mocha": "^9.2.2",
"prettier": "^2.7.1",
"typescript": "5.0.2"
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
export * from './system';

View file

@ -0,0 +1,44 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/system
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./system"), exports);

View file

@ -0,0 +1,26 @@
import * as Types from '../typebox';
export declare class TypeSystemDuplicateTypeKind extends Error {
constructor(kind: string);
}
export declare class TypeSystemDuplicateFormat extends Error {
constructor(kind: string);
}
/** Creates user defined types and formats and provides overrides for value checking behaviours */
export declare namespace TypeSystem {
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
let ExactOptionalPropertyTypes: boolean;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
let AllowArrayObjects: boolean;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
let AllowNaN: boolean;
/** Sets whether `null` should validate for void types. The default is `false` */
let AllowVoidNull: boolean;
/** Creates a new type */
function Type<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
/** Creates a new string format */
function Format<F extends string>(format: F, check: (value: string) => boolean): F;
/** @deprecated Use `TypeSystem.Type()` instead. */
function CreateType<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
/** @deprecated Use `TypeSystem.Format()` instead. */
function CreateFormat<F extends string>(format: F, check: (value: string) => boolean): F;
}

View file

@ -0,0 +1,90 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/system
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeSystem = exports.TypeSystemDuplicateFormat = exports.TypeSystemDuplicateTypeKind = void 0;
const Types = require("../typebox");
class TypeSystemDuplicateTypeKind extends Error {
constructor(kind) {
super(`Duplicate type kind '${kind}' detected`);
}
}
exports.TypeSystemDuplicateTypeKind = TypeSystemDuplicateTypeKind;
class TypeSystemDuplicateFormat extends Error {
constructor(kind) {
super(`Duplicate string format '${kind}' detected`);
}
}
exports.TypeSystemDuplicateFormat = TypeSystemDuplicateFormat;
/** Creates user defined types and formats and provides overrides for value checking behaviours */
var TypeSystem;
(function (TypeSystem) {
// ------------------------------------------------------------------------
// Assertion Policies
// ------------------------------------------------------------------------
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
TypeSystem.ExactOptionalPropertyTypes = false;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
TypeSystem.AllowArrayObjects = false;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
TypeSystem.AllowNaN = false;
/** Sets whether `null` should validate for void types. The default is `false` */
TypeSystem.AllowVoidNull = false;
// ------------------------------------------------------------------------
// String Formats and Types
// ------------------------------------------------------------------------
/** Creates a new type */
function Type(kind, check) {
if (Types.TypeRegistry.Has(kind))
throw new TypeSystemDuplicateTypeKind(kind);
Types.TypeRegistry.Set(kind, check);
return (options = {}) => Types.Type.Unsafe({ ...options, [Types.Kind]: kind });
}
TypeSystem.Type = Type;
/** Creates a new string format */
function Format(format, check) {
if (Types.FormatRegistry.Has(format))
throw new TypeSystemDuplicateFormat(format);
Types.FormatRegistry.Set(format, check);
return format;
}
TypeSystem.Format = Format;
// ------------------------------------------------------------------------
// Deprecated
// ------------------------------------------------------------------------
/** @deprecated Use `TypeSystem.Type()` instead. */
function CreateType(kind, check) {
return Type(kind, check);
}
TypeSystem.CreateType = CreateType;
/** @deprecated Use `TypeSystem.Format()` instead. */
function CreateFormat(format, check) {
return Format(format, check);
}
TypeSystem.CreateFormat = CreateFormat;
})(TypeSystem = exports.TypeSystem || (exports.TypeSystem = {}));

View file

@ -0,0 +1,717 @@
export declare const Modifier: unique symbol;
export declare const Hint: unique symbol;
export declare const Kind: unique symbol;
export declare const PatternBoolean = "(true|false)";
export declare const PatternNumber = "(0|[1-9][0-9]*)";
export declare const PatternString = "(.*)";
export declare const PatternBooleanExact: string;
export declare const PatternNumberExact: string;
export declare const PatternStringExact: string;
export type TupleToIntersect<T extends any[]> = T extends [infer I] ? I : T extends [infer I, ...infer R] ? I & TupleToIntersect<R> : never;
export type TupleToUnion<T extends any[]> = {
[K in keyof T]: T[K];
}[number];
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
export type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
export type Assert<T, E> = T extends E ? T : never;
export type Evaluate<T> = T extends infer O ? {
[K in keyof O]: O[K];
} : never;
export type Ensure<T> = T extends infer U ? U : never;
export type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export type TReadonly<T extends TSchema> = T & {
[Modifier]: 'Readonly';
};
export type TOptional<T extends TSchema> = T & {
[Modifier]: 'Optional';
};
export type TReadonlyOptional<T extends TSchema> = T & {
[Modifier]: 'ReadonlyOptional';
};
export interface SchemaOptions {
$schema?: string;
/** Id for this schema */
$id?: string;
/** Title of this schema */
title?: string;
/** Description of this schema */
description?: string;
/** Default value for this schema */
default?: any;
/** Example values matching this schema */
examples?: any;
[prop: string]: any;
}
export interface TKind {
[Kind]: string;
}
export interface TSchema extends SchemaOptions, TKind {
[Modifier]?: string;
[Hint]?: string;
params: unknown[];
static: unknown;
}
export type TAnySchema = TSchema | TAny | TArray | TBigInt | TBoolean | TConstructor | TDate | TEnum | TFunction | TInteger | TIntersect | TLiteral | TNot | TNull | TNumber | TObject | TPromise | TRecord | TRef | TString | TSymbol | TTemplateLiteral | TThis | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid;
export type TNumeric = TInteger | TNumber;
export interface NumericOptions<N extends number | bigint> extends SchemaOptions {
exclusiveMaximum?: N;
exclusiveMinimum?: N;
maximum?: N;
minimum?: N;
multipleOf?: N;
}
export interface TAny extends TSchema {
[Kind]: 'Any';
static: any;
}
export interface ArrayOptions extends SchemaOptions {
uniqueItems?: boolean;
minItems?: number;
maxItems?: number;
}
export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
[Kind]: 'Array';
static: Static<T, this['params']>[];
type: 'array';
items: T;
}
export interface TBigInt extends TSchema, NumericOptions<bigint> {
[Kind]: 'BigInt';
static: bigint;
type: 'null';
typeOf: 'BigInt';
}
export interface TBoolean extends TSchema {
[Kind]: 'Boolean';
static: boolean;
type: 'boolean';
}
export type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>;
export type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
export type TCompositeEvaluateArray<T extends readonly TSchema[], P extends unknown[]> = {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
};
export type TCompositeArray<T extends readonly TObject[]> = {
[K in keyof T]: T[K] extends TObject<infer P> ? P : {};
};
export type TCompositeProperties<I extends unknown, T extends readonly any[]> = Evaluate<T extends [infer A, ...infer B] ? TCompositeProperties<I & A, B> : I extends object ? I : {}>;
export interface TComposite<T extends TObject[] = TObject[]> extends TObject {
[Hint]: 'Composite';
static: Evaluate<TCompositeProperties<unknown, TCompositeEvaluateArray<T, this['params']>>>;
properties: TCompositeProperties<unknown, TCompositeArray<T>>;
}
export type TConstructorParameterArray<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
}];
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor';
static: new (...param: TConstructorParameterArray<T, this['params']>) => Static<U, this['params']>;
type: 'object';
instanceOf: 'Constructor';
parameters: T;
returns: U;
}
export interface DateOptions extends SchemaOptions {
exclusiveMaximumTimestamp?: number;
exclusiveMinimumTimestamp?: number;
maximumTimestamp?: number;
minimumTimestamp?: number;
}
export interface TDate extends TSchema, DateOptions {
[Kind]: 'Date';
static: Date;
type: 'object';
instanceOf: 'Date';
}
export interface TEnumOption<T> {
type: 'number' | 'string';
const: T;
}
export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema {
[Kind]: 'Union';
static: T[keyof T];
anyOf: TLiteral<string | number>[];
}
export type TExtends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema> = (Static<L> extends Static<R> ? T : U) extends infer O ? UnionToTuple<O> extends [infer X, infer Y] ? TUnion<[Assert<X, TSchema>, Assert<Y, TSchema>]> : Assert<O, TSchema> : never;
export type TExcludeTemplateLiteralResult<T extends string> = TString;
export type TExcludeTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Exclude<Static<T>, Static<U>> extends infer S ? TExcludeTemplateLiteralResult<Assert<S, string>> : never;
export type TExcludeArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? never : T[K];
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TExclude<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExcludeTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExcludeArray<S, U> : T extends U ? TNever : T;
export type TExtractTemplateLiteralResult<T extends string> = TString;
export type TExtractTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Extract<Static<T>, Static<U>> extends infer S ? TExtractTemplateLiteralResult<Assert<S, string>> : never;
export type TExtractArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? T[K] : never;
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TExtract<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExtractTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExtractArray<S, U> : T extends U ? T : T;
export type TFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
}];
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function';
static: (...param: TFunctionParameters<T, this['params']>) => Static<U, this['params']>;
type: 'object';
instanceOf: 'Function';
parameters: T;
returns: U;
}
export interface TInteger extends TSchema, NumericOptions<number> {
[Kind]: 'Integer';
static: number;
type: 'integer';
}
export type TUnevaluatedProperties = undefined | TSchema | boolean;
export interface IntersectOptions extends SchemaOptions {
unevaluatedProperties?: TUnevaluatedProperties;
}
export interface TIntersect<T extends TSchema[] = TSchema[]> extends TSchema, IntersectOptions {
[Kind]: 'Intersect';
static: TupleToIntersect<{
[K in keyof T]: Static<Assert<T[K], TSchema>, this['params']>;
}>;
type?: 'object';
allOf: [...T];
}
export type TKeyOfTuple<T extends TSchema> = {
[K in keyof Static<T>]: TLiteral<Assert<K, TLiteralValue>>;
} extends infer U ? UnionToTuple<Exclude<{
[K in keyof U]: U[K];
}[keyof U], undefined>> : never;
export type TKeyOf<T extends TSchema = TSchema> = (T extends TRecursive<infer S> ? TKeyOfTuple<S> : T extends TComposite ? TKeyOfTuple<T> : T extends TIntersect ? TKeyOfTuple<T> : T extends TUnion ? TKeyOfTuple<T> : T extends TObject ? TKeyOfTuple<T> : T extends TRecord<infer K> ? [K] : [
]) extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TLiteralValue = string | number | boolean;
export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema {
[Kind]: 'Literal';
static: T;
const: T;
}
export interface TNever extends TSchema {
[Kind]: 'Never';
static: never;
not: {};
}
export interface TNot<Not extends TSchema = TSchema, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Not';
static: Static<T>;
allOf: [{
not: Not;
}, T];
}
export interface TNull extends TSchema {
[Kind]: 'Null';
static: null;
type: 'null';
}
export interface TNumber extends TSchema, NumericOptions<number> {
[Kind]: 'Number';
static: number;
type: 'number';
}
export type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
}[keyof T];
export type ReadonlyPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
}[keyof T];
export type OptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
}[keyof T];
export type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>;
export type PropertiesReducer<T extends TProperties, R extends Record<keyof any, unknown>> = Evaluate<(Readonly<Partial<Pick<R, ReadonlyOptionalPropertyKeys<T>>>> & Readonly<Pick<R, ReadonlyPropertyKeys<T>>> & Partial<Pick<R, OptionalPropertyKeys<T>>> & Required<Pick<R, RequiredPropertyKeys<T>>>)>;
export type PropertiesReduce<T extends TProperties, P extends unknown[]> = PropertiesReducer<T, {
[K in keyof T]: Static<T[K], P>;
}>;
export type TProperties = Record<keyof any, TSchema>;
export type ObjectProperties<T> = T extends TObject<infer U> ? U : never;
export type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
export type TAdditionalProperties = undefined | TSchema | boolean;
export interface ObjectOptions extends SchemaOptions {
additionalProperties?: TAdditionalProperties;
minProperties?: number;
maxProperties?: number;
}
export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions {
[Kind]: 'Object';
static: PropertiesReduce<T, this['params']>;
additionalProperties?: TAdditionalProperties;
type: 'object';
properties: T;
required?: string[];
}
export type TOmitArray<T extends TSchema[], K extends keyof any> = Assert<{
[K2 in keyof T]: TOmit<Assert<T[K2], TSchema>, K>;
}, TSchema[]>;
export type TOmitProperties<T extends TProperties, K extends keyof any> = Evaluate<Assert<Omit<T, K>, TProperties>>;
export type TOmit<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TOmit<S, K>> : T extends TComposite<infer S> ? TComposite<TOmitArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TOmitArray<S, K>> : T extends TUnion<infer S> ? TUnion<TOmitArray<S, K>> : T extends TObject<infer S> ? TObject<TOmitProperties<S, K>> : T;
export type TParameters<T extends TFunction> = TTuple<T['parameters']>;
export type TPartialObjectArray<T extends TObject[]> = Assert<{
[K in keyof T]: TPartial<Assert<T[K], TObject>>;
}, TObject[]>;
export type TPartialArray<T extends TSchema[]> = Assert<{
[K in keyof T]: TPartial<Assert<T[K], TSchema>>;
}, TSchema[]>;
export type TPartialProperties<T extends TProperties> = Evaluate<Assert<{
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> : T[K] extends TReadonly<infer U> ? TReadonlyOptional<U> : T[K] extends TOptional<infer U> ? TOptional<U> : TOptional<T[K]>;
}, TProperties>>;
export type TPartial<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TPartial<S>> : T extends TComposite<infer S> ? TComposite<TPartialArray<S>> : T extends TIntersect<infer S> ? TIntersect<TPartialArray<S>> : T extends TUnion<infer S> ? TUnion<TPartialArray<S>> : T extends TObject<infer S> ? TObject<TPartialProperties<S>> : T;
export type TPickArray<T extends TSchema[], K extends keyof any> = {
[K2 in keyof T]: TPick<Assert<T[K2], TSchema>, K>;
};
export type TPickProperties<T extends TProperties, K extends keyof any> = Pick<T, Assert<Extract<K, keyof T>, keyof T>> extends infer R ? ({
[K in keyof R]: Assert<R[K], TSchema> extends TSchema ? R[K] : never;
}) : never;
export type TPick<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TPick<S, K>> : T extends TComposite<infer S> ? TComposite<TPickArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TPickArray<S, K>> : T extends TUnion<infer S> ? TUnion<TPickArray<S, K>> : T extends TObject<infer S> ? TObject<TPickProperties<S, K>> : T;
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise';
static: Promise<Static<T, this['params']>>;
type: 'object';
instanceOf: 'Promise';
item: TSchema;
}
export type RecordTemplateLiteralObjectType<K extends TTemplateLiteral, T extends TSchema> = Ensure<TObject<Evaluate<{
[_ in Static<K>]: T;
}>>>;
export type RecordTemplateLiteralType<K extends TTemplateLiteral, T extends TSchema> = IsTemplateLiteralFinite<K> extends true ? RecordTemplateLiteralObjectType<K, T> : TRecord<K, T>;
export type RecordUnionLiteralType<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema> = Static<K> extends string ? Ensure<TObject<{
[X in Static<K>]: T;
}>> : never;
export type RecordLiteralType<K extends TLiteral<string | number>, T extends TSchema> = Ensure<TObject<{
[K2 in K['const']]: T;
}>>;
export type RecordNumberType<K extends TInteger | TNumber, T extends TSchema> = Ensure<TRecord<K, T>>;
export type RecordStringType<K extends TString, T extends TSchema> = Ensure<TRecord<K, T>>;
export type RecordKey = TUnion<TLiteral<string | number>[]> | TLiteral<string | number> | TTemplateLiteral | TInteger | TNumber | TString;
export interface TRecord<K extends RecordKey = RecordKey, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Record';
static: Record<Static<K>, Static<T, this['params']>>;
type: 'object';
patternProperties: {
[pattern: string]: T;
};
additionalProperties: false;
}
export interface TThis extends TSchema {
[Kind]: 'This';
static: this['params'][0];
$ref: string;
}
export type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
export interface TRecursive<T extends TSchema> extends TSchema {
[Hint]: 'Recursive';
static: TRecursiveReduce<T>;
}
export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref';
static: Static<T, this['params']>;
$ref: string;
}
export type TReturnType<T extends TFunction> = T['returns'];
export type TRequiredArray<T extends TSchema[]> = Assert<{
[K in keyof T]: TRequired<Assert<T[K], TSchema>>;
}, TSchema[]>;
export type TRequiredProperties<T extends TProperties> = Evaluate<Assert<{
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonly<U> : T[K] extends TReadonly<infer U> ? TReadonly<U> : T[K] extends TOptional<infer U> ? U : T[K];
}, TProperties>>;
export type TRequired<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TRequired<S>> : T extends TComposite<infer S> ? TComposite<TRequiredArray<S>> : T extends TIntersect<infer S> ? TIntersect<TRequiredArray<S>> : T extends TUnion<infer S> ? TUnion<TRequiredArray<S>> : T extends TObject<infer S> ? TObject<TRequiredProperties<S>> : T;
export type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex';
export interface StringOptions<Format extends string> extends SchemaOptions {
minLength?: number;
maxLength?: number;
pattern?: string;
format?: Format;
contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64';
contentMediaType?: string;
}
export interface TString<Format extends string = string> extends TSchema, StringOptions<Format> {
[Kind]: 'String';
static: string;
type: 'string';
}
export type SymbolValue = string | number | undefined;
export interface TSymbol extends TSchema, SchemaOptions {
[Kind]: 'Symbol';
static: symbol;
type: 'null';
typeOf: 'Symbol';
}
export type IsTemplateLiteralFiniteCheck<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TUnion<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TString ? false : T extends TBoolean ? false : T extends TNumber ? false : T extends TInteger ? false : T extends TBigInt ? false : T extends TLiteral ? true : false;
export type IsTemplateLiteralFiniteArray<T extends TTemplateLiteralKind[]> = T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : IsTemplateLiteralFiniteArray<Assert<R, TTemplateLiteralKind[]>> : T extends [infer L] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : true : true;
export type IsTemplateLiteralFinite<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<U> : false;
export type TTemplateLiteralKind = TUnion | TLiteral | TInteger | TTemplateLiteral | TNumber | TBigInt | TString | TBoolean | TNever;
export type TTemplateLiteralConst<T, Acc extends string> = T extends TUnion<infer U> ? {
[K in keyof U]: TTemplateLiteralUnion<Assert<[U[K]], TTemplateLiteralKind[]>, Acc>;
}[number] : T extends TTemplateLiteral ? `${Static<T>}` : T extends TLiteral<infer U> ? `${U}` : T extends TString ? `${string}` : T extends TNumber ? `${number}` : T extends TBigInt ? `${bigint}` : T extends TBoolean ? `${boolean}` : never;
export type TTemplateLiteralUnion<T extends TTemplateLiteralKind[], Acc extends string = ''> = T extends [infer L, ...infer R] ? `${TTemplateLiteralConst<L, Acc>}${TTemplateLiteralUnion<Assert<R, TTemplateLiteralKind[]>, Acc>}` : T extends [infer L] ? `${TTemplateLiteralConst<L, Acc>}${Acc}` : Acc;
export interface TTemplateLiteral<T extends TTemplateLiteralKind[] = TTemplateLiteralKind[]> extends TSchema {
[Kind]: 'TemplateLiteral';
static: TTemplateLiteralUnion<T>;
type: 'string';
pattern: string;
}
export type TTupleIntoArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? Assert<R, TSchema[]> : never;
export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Tuple';
static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K];
};
type: 'array';
items?: T;
additionalItems?: false;
minItems: number;
maxItems: number;
}
export interface TUndefined extends TSchema {
[Kind]: 'Undefined';
static: undefined;
type: 'null';
typeOf: 'Undefined';
}
export type TUnionOfLiteralArray<T extends TLiteral<string>[]> = {
[K in keyof T]: Assert<T[K], TLiteral>['const'];
}[number];
export type TUnionOfLiteral<T extends TUnion<TLiteral<string>[]>> = TUnionOfLiteralArray<T['anyOf']>;
export type TUnionResult<T extends TSchema[]> = T extends [] ? TNever : T extends [infer S] ? S : TUnion<T>;
export type TUnionTemplateLiteral<T extends TTemplateLiteral, S extends string = Static<T>> = (string);
export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Union';
static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never;
}[number];
anyOf: T;
}
export interface Uint8ArrayOptions extends SchemaOptions {
maxByteLength?: number;
minByteLength?: number;
}
export interface TUint8Array extends TSchema, Uint8ArrayOptions {
[Kind]: 'Uint8Array';
static: Uint8Array;
instanceOf: 'Uint8Array';
type: 'object';
}
export interface TUnknown extends TSchema {
[Kind]: 'Unknown';
static: unknown;
}
export interface UnsafeOptions extends SchemaOptions {
[Kind]?: string;
}
export interface TUnsafe<T> extends TSchema {
[Kind]: string;
static: T;
}
export interface TVoid extends TSchema {
[Kind]: 'Void';
static: void;
type: 'null';
typeOf: 'Void';
}
/** Creates a TypeScript static type from a TypeBox type */
export type Static<T extends TSchema, P extends unknown[] = []> = (T & {
params: P;
})['static'];
export type TypeRegistryValidationFunction<TSchema> = (schema: TSchema, value: unknown) => boolean;
/** A registry for user defined types */
export declare namespace TypeRegistry {
/** Returns the entries in this registry */
function Entries(): Map<string, TypeRegistryValidationFunction<any>>;
/** Clears all user defined types */
function Clear(): void;
/** Returns true if this registry contains this kind */
function Has(kind: string): boolean;
/** Sets a validation function for a user defined type */
function Set<TSchema = unknown>(kind: string, func: TypeRegistryValidationFunction<TSchema>): void;
/** Gets a custom validation function for a user defined type */
function Get(kind: string): TypeRegistryValidationFunction<any> | undefined;
}
export type FormatRegistryValidationFunction = (value: string) => boolean;
/** A registry for user defined string formats */
export declare namespace FormatRegistry {
/** Returns the entries in this registry */
function Entries(): Map<string, FormatRegistryValidationFunction>;
/** Clears all user defined string formats */
function Clear(): void;
/** Returns true if the user defined string format exists */
function Has(format: string): boolean;
/** Sets a validation function for a user defined string format */
function Set(format: string, func: FormatRegistryValidationFunction): void;
/** Gets a validation function for a user defined string format */
function Get(format: string): FormatRegistryValidationFunction | undefined;
}
export declare class TypeGuardUnknownTypeError extends Error {
readonly schema: unknown;
constructor(schema: unknown);
}
/** Provides functions to test if JavaScript values are TypeBox types */
export declare namespace TypeGuard {
/** Returns true if the given schema is TAny */
function TAny(schema: unknown): schema is TAny;
/** Returns true if the given schema is TArray */
function TArray(schema: unknown): schema is TArray;
/** Returns true if the given schema is TBigInt */
function TBigInt(schema: unknown): schema is TBigInt;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema: unknown): schema is TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema: unknown): schema is TConstructor;
/** Returns true if the given schema is TDate */
function TDate(schema: unknown): schema is TDate;
/** Returns true if the given schema is TFunction */
function TFunction(schema: unknown): schema is TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema: unknown): schema is TInteger;
/** Returns true if the given schema is TIntersect */
function TIntersect(schema: unknown): schema is TIntersect;
/** Returns true if the given schema is TKind */
function TKind(schema: unknown): schema is Record<typeof Kind | string, unknown>;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema: unknown): schema is TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema: unknown): schema is TNever;
/** Returns true if the given schema is TNot */
function TNot(schema: unknown): schema is TNot;
/** Returns true if the given schema is TNull */
function TNull(schema: unknown): schema is TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema: unknown): schema is TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema: unknown): schema is TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema: unknown): schema is TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema: unknown): schema is TRecord;
/** Returns true if the given schema is TRef */
function TRef(schema: unknown): schema is TRef;
/** Returns true if the given schema is TString */
function TString(schema: unknown): schema is TString;
/** Returns true if the given schema is TSymbol */
function TSymbol(schema: unknown): schema is TSymbol;
/** Returns true if the given schema is TTemplateLiteral */
function TTemplateLiteral(schema: unknown): schema is TTemplateLiteral;
/** Returns true if the given schema is TThis */
function TThis(schema: unknown): schema is TThis;
/** Returns true if the given schema is TTuple */
function TTuple(schema: unknown): schema is TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema: unknown): schema is TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema: unknown): schema is TUnion;
/** Returns true if the given schema is TUnion<Literal<string>[]> */
function TUnionLiteral(schema: unknown): schema is TUnion<TLiteral<string>[]>;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema: unknown): schema is TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema: unknown): schema is TUnknown;
/** Returns true if the given schema is a raw TUnsafe */
function TUnsafe(schema: unknown): schema is TUnsafe<unknown>;
/** Returns true if the given schema is TVoid */
function TVoid(schema: unknown): schema is TVoid;
/** Returns true if this schema has the ReadonlyOptional modifier */
function TReadonlyOptional<T extends TSchema>(schema: T): schema is TReadonlyOptional<T>;
/** Returns true if this schema has the Readonly modifier */
function TReadonly<T extends TSchema>(schema: T): schema is TReadonly<T>;
/** Returns true if this schema has the Optional modifier */
function TOptional<T extends TSchema>(schema: T): schema is TOptional<T>;
/** Returns true if the given schema is TSchema */
function TSchema(schema: unknown): schema is TSchema;
}
/** Fast undefined check used for properties of type undefined */
export declare namespace ExtendsUndefined {
function Check(schema: TSchema): boolean;
}
export declare enum TypeExtendsResult {
Union = 0,
True = 1,
False = 2
}
export declare namespace TypeExtends {
function Extends(left: TSchema, right: TSchema): TypeExtendsResult;
}
/** Specialized Clone for Types */
export declare namespace TypeClone {
/** Clones a type. */
function Clone<T extends TSchema>(schema: T, options: SchemaOptions): T;
}
export declare namespace ObjectMap {
function Map<T = TSchema>(schema: TSchema, callback: (object: TObject) => TObject, options: SchemaOptions): T;
}
export declare namespace KeyResolver {
function Resolve<T extends TSchema>(schema: T): string[];
}
export declare namespace TemplateLiteralPattern {
function Create(kinds: TTemplateLiteralKind[]): string;
}
export declare namespace TemplateLiteralResolver {
function Resolve(template: TTemplateLiteral): TString | TUnion | TLiteral;
}
export declare class TemplateLiteralParserError extends Error {
constructor(message: string);
}
export declare namespace TemplateLiteralParser {
type Expression = And | Or | Const;
type Const = {
type: 'const';
const: string;
};
type And = {
type: 'and';
expr: Expression[];
};
type Or = {
type: 'or';
expr: Expression[];
};
/** Parses a pattern and returns an expression tree */
function Parse(pattern: string): Expression;
/** Parses a pattern and strips forward and trailing ^ and $ */
function ParseExact(pattern: string): Expression;
}
export declare namespace TemplateLiteralFinite {
function Check(expression: TemplateLiteralParser.Expression): boolean;
}
export declare namespace TemplateLiteralGenerator {
function Generate(expression: TemplateLiteralParser.Expression): IterableIterator<string>;
}
export declare class TypeBuilder {
/** `[Utility]` Creates a schema without `static` and `params` types */
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
/** `[Standard]` Omits compositing symbols from this schema */
Strict<T extends TSchema>(schema: T): T;
}
export declare class StandardTypeBuilder extends TypeBuilder {
/** `[Modifier]` Creates a Optional property */
Optional<T extends TSchema>(schema: T): TOptional<T>;
/** `[Modifier]` Creates a ReadonlyOptional property */
ReadonlyOptional<T extends TSchema>(schema: T): TReadonlyOptional<T>;
/** `[Modifier]` Creates a Readonly object or property */
Readonly<T extends TSchema>(schema: T): TReadonly<T>;
/** `[Standard]` Creates an Any type */
Any(options?: SchemaOptions): TAny;
/** `[Standard]` Creates an Array type */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** `[Standard]` Creates a Boolean type */
Boolean(options?: SchemaOptions): TBoolean;
/** `[Standard]` Creates a Composite object type. */
Composite<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TComposite<T>;
/** `[Standard]` Creates a Enum type */
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
/** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */
Extends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema>(left: L, right: R, trueType: T, falseType: U, options?: SchemaOptions): TExtends<L, R, T, U>;
/** `[Standard]` Excludes from the left type any type that is not assignable to the right */
Exclude<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExclude<L, R>;
/** `[Standard]` Extracts from the left type any type that is assignable to the right */
Extract<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExtract<L, R>;
/** `[Standard]` Creates an Integer type */
Integer(options?: NumericOptions<number>): TInteger;
/** `[Standard]` Creates a Intersect type */
Intersect(allOf: [], options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Intersect type */
Intersect<T extends [TSchema]>(allOf: [...T], options?: SchemaOptions): T[0];
Intersect<T extends TSchema[]>(allOf: [...T], options?: IntersectOptions): TIntersect<T>;
/** `[Standard]` Creates a KeyOf type */
KeyOf<T extends TSchema>(schema: T, options?: SchemaOptions): TKeyOf<T>;
/** `[Standard]` Creates a Literal type */
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
/** `[Standard]` Creates a Never type */
Never(options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Not type. The first argument is the disallowed type, the second is the allowed. */
Not<N extends TSchema, T extends TSchema>(not: N, schema: T, options?: SchemaOptions): TNot<N, T>;
/** `[Standard]` Creates a Null type */
Null(options?: SchemaOptions): TNull;
/** `[Standard]` Creates a Number type */
Number(options?: NumericOptions<number>): TNumber;
/** `[Standard]` Creates an Object type */
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TOmit<T, K[number]>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TOmit<T, TUnionOfLiteral<K>>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TOmit<T, K['const']>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TOmit<T, never>;
/** `[Standard]` Creates a mapped type where all properties are Optional */
Partial<T extends TSchema>(schema: T, options?: ObjectOptions): TPartial<T>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TPick<T, K[number]>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TPick<T, TUnionOfLiteral<K>>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TPick<T, K['const']>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TPick<T, never>;
/** `[Standard]` Creates a Record type */
Record<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordUnionLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TLiteral<string | number>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TTemplateLiteral, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordTemplateLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TInteger | TNumber, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordNumberType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TString, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordStringType<K, T>;
/** `[Standard]` Creates a Recursive type */
Recursive<T extends TSchema>(callback: (thisType: TThis) => T, options?: SchemaOptions): TRecursive<T>;
/** `[Standard]` Creates a Ref type. The referenced type must contain a $id */
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
/** `[Standard]` Creates a mapped type where all properties are Required */
Required<T extends TSchema>(schema: T, options?: SchemaOptions): TRequired<T>;
/** `[Standard]` Creates a String type */
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
/** `[Standard]` Creates a template literal type */
TemplateLiteral<T extends TTemplateLiteralKind[]>(kinds: [...T], options?: SchemaOptions): TTemplateLiteral<T>;
/** `[Standard]` Creates a Tuple type */
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
/** `[Standard]` Creates a Union type */
Union(anyOf: [], options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Union type */
Union<T extends [TSchema]>(anyOf: [...T], options?: SchemaOptions): T[0];
/** `[Standard]` Creates a Union type */
Union<T extends TSchema[]>(anyOf: [...T], options?: SchemaOptions): TUnion<T>;
/** `[Experimental]` Remaps a TemplateLiteral into a Union representation. This function is known to cause TS compiler crashes for finite templates with large generation counts. Use with caution. */
Union<T extends TTemplateLiteral>(template: T): TUnionTemplateLiteral<T>;
/** `[Standard]` Creates an Unknown type */
Unknown(options?: SchemaOptions): TUnknown;
/** `[Standard]` Creates a Unsafe type that infers for the generic argument */
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
}
export declare class ExtendedTypeBuilder extends StandardTypeBuilder {
/** `[Extended]` Creates a BigInt type */
BigInt(options?: NumericOptions<bigint>): TBigInt;
/** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
/** `[Extended]` Creates a Constructor type */
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TTupleIntoArray<T>, U>;
/** `[Extended]` Creates a Constructor type */
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
/** `[Extended]` Creates a Date type */
Date(options?: DateOptions): TDate;
/** `[Extended]` Creates a Function type */
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TTupleIntoArray<T>, U>;
/** `[Extended]` Creates a Function type */
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
/** `[Extended]` Extracts the InstanceType from the given Constructor */
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
/** `[Extended]` Extracts the Parameters from the given Function type */
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
/** `[Extended]` Creates a Promise type */
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
/** `[Extended]` Creates a regular expression type */
RegEx(regex: RegExp, options?: SchemaOptions): TString;
/** `[Extended]` Extracts the ReturnType from the given Function */
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
/** `[Extended]` Creates a Symbol type */
Symbol(options?: SchemaOptions): TSymbol;
/** `[Extended]` Creates a Undefined type */
Undefined(options?: SchemaOptions): TUndefined;
/** `[Extended]` Creates a Uint8Array type */
Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
/** `[Extended]` Creates a Void type */
Void(options?: SchemaOptions): TVoid;
}
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
export declare const StandardType: StandardTypeBuilder;
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
export declare const Type: ExtendedTypeBuilder;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,30 @@
import * as Types from '../typebox';
export declare class ValueCastReferenceTypeError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare class ValueCastArrayUniqueItemsTypeError extends Error {
readonly schema: Types.TSchema;
readonly value: unknown;
constructor(schema: Types.TSchema, value: unknown);
}
export declare class ValueCastNeverTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastRecursiveTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCast {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
function Cast<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): Types.Static<T>;
}

View file

@ -0,0 +1,372 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCast = exports.ValueCastDereferenceError = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0;
const Types = require("../typebox");
const create_1 = require("./create");
const check_1 = require("./check");
const clone_1 = require("./clone");
// ----------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------
class ValueCastReferenceTypeError extends Error {
constructor(schema) {
super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError;
class ValueCastArrayUniqueItemsTypeError extends Error {
constructor(schema, value) {
super('ValueCast: Array cast produced invalid data due to uniqueItems constraint');
this.schema = schema;
this.value = value;
}
}
exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError;
class ValueCastNeverTypeError extends Error {
constructor(schema) {
super('ValueCast: Never types cannot be cast');
this.schema = schema;
}
}
exports.ValueCastNeverTypeError = ValueCastNeverTypeError;
class ValueCastRecursiveTypeError extends Error {
constructor(schema) {
super('ValueCast.Recursive: Cannot cast recursive schemas');
this.schema = schema;
}
}
exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError;
class ValueCastUnknownTypeError extends Error {
constructor(schema) {
super('ValueCast: Unknown type');
this.schema = schema;
}
}
exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError;
class ValueCastDereferenceError extends Error {
constructor(schema) {
super(`ValueCast: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCastDereferenceError = ValueCastDereferenceError;
// ----------------------------------------------------------------------------------------------
// The following will score a schema against a value. For objects, the score is the tally of
// points awarded for each property of the value. Property points are (1.0 / propertyCount)
// to prevent large property counts biasing results. Properties that match literal values are
// maximally awarded as literals are typically used as union discriminator fields.
// ----------------------------------------------------------------------------------------------
var UnionCastCreate;
(function (UnionCastCreate) {
function Score(schema, references, value) {
if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) {
const object = schema;
const keys = Object.keys(value);
const entries = globalThis.Object.entries(object.properties);
const [point, max] = [1 / entries.length, entries.length];
return entries.reduce((acc, [key, schema]) => {
const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0;
const checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0;
const exists = keys.includes(key) ? point : 0;
return acc + (literal + checks + exists);
}, 0);
}
else {
return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0;
}
}
function Select(union, references, value) {
let [select, best] = [union.anyOf[0], 0];
for (const schema of union.anyOf) {
const score = Score(schema, references, value);
if (score > best) {
select = schema;
best = score;
}
}
return select;
}
function Create(union, references, value) {
if (union.default !== undefined) {
return union.default;
}
else {
const schema = Select(union, references, value);
return ValueCast.Cast(schema, references, value);
}
}
UnionCastCreate.Create = Create;
})(UnionCastCreate || (UnionCastCreate = {}));
var ValueCast;
(function (ValueCast) {
// ----------------------------------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------------------------------
function IsObject(value) {
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
function IsNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
function IsString(value) {
return typeof value === 'string';
}
// ----------------------------------------------------------------------------------------------
// Cast
// ----------------------------------------------------------------------------------------------
function Any(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Array(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
const minimum = IsNumber(schema.minItems) && created.length < schema.minItems ? [...created, ...globalThis.Array.from({ length: schema.minItems - created.length }, () => null)] : created;
const maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum;
const casted = maximum.map((value) => Visit(schema.items, references, value));
if (schema.uniqueItems !== true)
return casted;
const unique = [...new Set(casted)];
if (!check_1.ValueCheck.Check(schema, references, unique))
throw new ValueCastArrayUniqueItemsTypeError(schema, unique);
return unique;
}
function BigInt(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Boolean(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Constructor(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.returns.required || []);
const result = function () { };
for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) {
if (!required.has(key) && value.prototype[key] === undefined)
continue;
result.prototype[key] = Visit(property, references, value.prototype[key]);
}
return result;
}
function Date(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Function(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Integer(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Intersect(schema, references, value) {
const created = create_1.ValueCreate.Create(schema, references);
const mapped = IsObject(created) && IsObject(value) ? { ...created, ...value } : value;
return check_1.ValueCheck.Check(schema, references, mapped) ? mapped : create_1.ValueCreate.Create(schema, references);
}
function Literal(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Never(schema, references, value) {
throw new ValueCastNeverTypeError(schema);
}
function Not(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema.allOf[1], references);
}
function Null(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Number(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Object(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return value;
if (value === null || typeof value !== 'object')
return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.required || []);
const result = {};
for (const [key, property] of globalThis.Object.entries(schema.properties)) {
if (!required.has(key) && value[key] === undefined)
continue;
result[key] = Visit(property, references, value[key]);
}
// additional schema properties
if (typeof schema.additionalProperties === 'object') {
const propertyNames = globalThis.Object.getOwnPropertyNames(schema.properties);
for (const propertyName of globalThis.Object.getOwnPropertyNames(value)) {
if (propertyNames.includes(propertyName))
continue;
result[propertyName] = Visit(schema.additionalProperties, references, value[propertyName]);
}
}
return result;
}
function Promise(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Record(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value) || value instanceof globalThis.Date)
return create_1.ValueCreate.Create(schema, references);
const subschemaPropertyName = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
const subschema = schema.patternProperties[subschemaPropertyName];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(subschema, references, propValue);
}
return result;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCastDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Symbol(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function TemplateLiteral(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCastDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
if (!globalThis.Array.isArray(value))
return create_1.ValueCreate.Create(schema, references);
if (schema.items === undefined)
return [];
return schema.items.map((schema, index) => Visit(schema, references, value[index]));
}
function Undefined(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Union(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : UnionCastCreate.Create(schema, references, value);
}
function Uint8Array(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Unknown(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Void(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function UserDefined(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Not':
return Not(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCastUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
ValueCast.Visit = Visit;
function Cast(schema, references, value) {
return Visit(schema, references, clone_1.ValueClone.Clone(value));
}
ValueCast.Cast = Cast;
})(ValueCast = exports.ValueCast || (exports.ValueCast = {}));

View file

@ -0,0 +1,12 @@
import * as Types from '../typebox';
export declare class ValueCheckUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCheckDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCheck {
function Check<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): boolean;
}

View file

@ -0,0 +1,484 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCheck = exports.ValueCheckDereferenceError = exports.ValueCheckUnknownTypeError = void 0;
const Types = require("../typebox");
const index_1 = require("../system/index");
const hash_1 = require("./hash");
// -------------------------------------------------------------------------
// Errors
// -------------------------------------------------------------------------
class ValueCheckUnknownTypeError extends Error {
constructor(schema) {
super(`ValueCheck: ${schema[Types.Kind] ? `Unknown type '${schema[Types.Kind]}'` : 'Unknown type'}`);
this.schema = schema;
}
}
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
class ValueCheckDereferenceError extends Error {
constructor(schema) {
super(`ValueCheck: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCheckDereferenceError = ValueCheckDereferenceError;
var ValueCheck;
(function (ValueCheck) {
// ----------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsInteger(value) {
return globalThis.Number.isInteger(value);
}
function IsString(value) {
return typeof value === 'string';
}
function IsDefined(value) {
return value !== undefined;
}
// ----------------------------------------------------------------------
// Policies
// ----------------------------------------------------------------------
function IsExactOptionalProperty(value, key) {
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
}
function IsObject(value) {
const result = typeof value === 'object' && value !== null;
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
}
function IsRecordObject(value) {
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
}
function IsNumber(value) {
const result = typeof value === 'number';
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
}
function IsVoid(value) {
const result = value === undefined;
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
function Any(schema, references, value) {
return true;
}
function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
return false;
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
return false;
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = hash_1.ValueHash.Create(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
return false;
}
return value.every((value) => Visit(schema.items, references, value));
}
function BigInt(schema, references, value) {
if (!IsBigInt(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Boolean(schema, references, value) {
return typeof value === 'boolean';
}
function Constructor(schema, references, value) {
return Visit(schema.returns, references, value.prototype);
}
function Date(schema, references, value) {
if (!(value instanceof globalThis.Date)) {
return false;
}
if (!IsNumber(value.getTime())) {
return false;
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
return false;
}
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
return false;
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
return false;
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
return false;
}
return true;
}
function Function(schema, references, value) {
return typeof value === 'function';
}
function Integer(schema, references, value) {
if (!IsInteger(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Intersect(schema, references, value) {
if (!schema.allOf.every((schema) => Visit(schema, references, value))) {
return false;
}
else if (schema.unevaluatedProperties === false) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => schemaKeys.includes(key));
}
else if (Types.TypeGuard.TSchema(schema.unevaluatedProperties)) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => schemaKeys.includes(key) || Visit(schema.unevaluatedProperties, references, value[key]));
}
else {
return true;
}
}
function Literal(schema, references, value) {
return value === schema.const;
}
function Never(schema, references, value) {
return false;
}
function Not(schema, references, value) {
return !Visit(schema.allOf[0].not, references, value) && Visit(schema.allOf[1], references, value);
}
function Null(schema, references, value) {
return value === null;
}
function Number(schema, references, value) {
if (!IsNumber(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Object(schema, references, value) {
if (!IsObject(value)) {
return false;
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
return false;
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
return false;
}
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
if (!Visit(property, references, value[knownKey])) {
return false;
}
if (Types.ExtendsUndefined.Check(property)) {
return knownKey in value;
}
}
else {
if (IsExactOptionalProperty(value, knownKey) && !Visit(property, references, value[knownKey])) {
return false;
}
}
}
if (schema.additionalProperties === false) {
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
// optimization: value is valid if schemaKey length matches the valueKey length
if (schema.required && schema.required.length === knownKeys.length && valueKeys.length === knownKeys.length) {
return true;
}
else {
return valueKeys.every((valueKey) => knownKeys.includes(valueKey));
}
}
else if (typeof schema.additionalProperties === 'object') {
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => knownKeys.includes(key) || Visit(schema.additionalProperties, references, value[key]));
}
else {
return true;
}
}
function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function';
}
function Record(schema, references, value) {
if (!IsRecordObject(value)) {
return false;
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
return false;
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
return false;
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
return false;
}
for (const propValue of globalThis.Object.values(value)) {
if (!Visit(valueSchema, references, propValue))
return false;
}
return true;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCheckDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
if (!IsString(value)) {
return false;
}
if (IsDefined(schema.minLength)) {
if (!(value.length >= schema.minLength))
return false;
}
if (IsDefined(schema.maxLength)) {
if (!(value.length <= schema.maxLength))
return false;
}
if (IsDefined(schema.pattern)) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value))
return false;
}
if (IsDefined(schema.format)) {
if (!Types.FormatRegistry.Has(schema.format))
return false;
const func = Types.FormatRegistry.Get(schema.format);
return func(value);
}
return true;
}
function Symbol(schema, references, value) {
if (!(typeof value === 'symbol')) {
return false;
}
return true;
}
function TemplateLiteral(schema, references, value) {
if (!IsString(value)) {
return false;
}
return new RegExp(schema.pattern).test(value);
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCheckDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (schema.items === undefined && !(value.length === 0)) {
return false;
}
if (!(value.length === schema.maxItems)) {
return false;
}
if (!schema.items) {
return true;
}
for (let i = 0; i < schema.items.length; i++) {
if (!Visit(schema.items[i], references, value[i]))
return false;
}
return true;
}
function Undefined(schema, references, value) {
return value === undefined;
}
function Union(schema, references, value) {
return schema.anyOf.some((inner) => Visit(inner, references, value));
}
function Uint8Array(schema, references, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return false;
}
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
return false;
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
return false;
}
return true;
}
function Unknown(schema, references, value) {
return true;
}
function Void(schema, references, value) {
return IsVoid(value);
}
function UserDefined(schema, references, value) {
if (!Types.TypeRegistry.Has(schema[Types.Kind]))
return false;
const func = Types.TypeRegistry.Get(schema[Types.Kind]);
return func(schema, value);
}
function Visit(schema, references, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Not':
return Not(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCheckUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
function Check(schema, references, value) {
return Visit(schema, references, value);
}
ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));

View file

@ -0,0 +1,3 @@
export declare namespace ValueClone {
function Clone<T extends unknown>(value: T): T;
}

View file

@ -0,0 +1,71 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueClone = void 0;
const is_1 = require("./is");
var ValueClone;
(function (ValueClone) {
function Array(value) {
return value.map((element) => Clone(element));
}
function Date(value) {
return new globalThis.Date(value.toISOString());
}
function Object(value) {
const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)];
return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {});
}
function TypedArray(value) {
return value.slice();
}
function Value(value) {
return value;
}
function Clone(value) {
if (is_1.Is.Date(value)) {
return Date(value);
}
else if (is_1.Is.Object(value)) {
return Object(value);
}
else if (is_1.Is.Array(value)) {
return Array(value);
}
else if (is_1.Is.TypedArray(value)) {
return TypedArray(value);
}
else if (is_1.Is.Value(value)) {
return Value(value);
}
else {
throw new Error('ValueClone: Unable to clone value');
}
}
ValueClone.Clone = Clone;
})(ValueClone = exports.ValueClone || (exports.ValueClone = {}));

View file

@ -0,0 +1,13 @@
import * as Types from '../typebox';
export declare class ValueConvertUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueConvertDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueConvert {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): unknown;
function Convert<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): unknown;
}

View file

@ -0,0 +1,372 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueConvert = exports.ValueConvertDereferenceError = exports.ValueConvertUnknownTypeError = void 0;
const Types = require("../typebox");
const clone_1 = require("./clone");
const check_1 = require("./check");
// ----------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------
class ValueConvertUnknownTypeError extends Error {
constructor(schema) {
super('ValueConvert: Unknown type');
this.schema = schema;
}
}
exports.ValueConvertUnknownTypeError = ValueConvertUnknownTypeError;
class ValueConvertDereferenceError extends Error {
constructor(schema) {
super(`ValueConvert: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueConvertDereferenceError = ValueConvertDereferenceError;
var ValueConvert;
(function (ValueConvert) {
// ----------------------------------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------------------------------
function IsObject(value) {
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
function IsDate(value) {
return typeof value === 'object' && value instanceof globalThis.Date;
}
function IsSymbol(value) {
return typeof value === 'symbol';
}
function IsString(value) {
return typeof value === 'string';
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
function IsStringNumeric(value) {
return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value));
}
function IsValueToString(value) {
return IsBigInt(value) || IsBoolean(value) || IsNumber(value);
}
function IsValueTrue(value) {
return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === globalThis.BigInt('1')) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
}
function IsValueFalse(value) {
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === globalThis.BigInt('0')) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
}
function IsTimeStringWithTimeZone(value) {
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
}
function IsTimeStringWithoutTimeZone(value) {
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
}
function IsDateTimeStringWithTimeZone(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
}
function IsDateTimeStringWithoutTimeZone(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
}
function IsDateString(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\d$/i.test(value);
}
// ----------------------------------------------------------------------------------------------
// Convert
// ----------------------------------------------------------------------------------------------
function TryConvertLiteralString(value, target) {
const conversion = TryConvertString(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteralNumber(value, target) {
const conversion = TryConvertNumber(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteralBoolean(value, target) {
const conversion = TryConvertBoolean(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteral(schema, value) {
if (typeof schema.const === 'string') {
return TryConvertLiteralString(value, schema.const);
}
else if (typeof schema.const === 'number') {
return TryConvertLiteralNumber(value, schema.const);
}
else if (typeof schema.const === 'boolean') {
return TryConvertLiteralBoolean(value, schema.const);
}
else {
return clone_1.ValueClone.Clone(value);
}
}
function TryConvertBoolean(value) {
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
}
function TryConvertBigInt(value) {
return IsStringNumeric(value) ? globalThis.BigInt(parseInt(value)) : IsNumber(value) ? globalThis.BigInt(value | 0) : IsValueFalse(value) ? 0 : IsValueTrue(value) ? 1 : value;
}
function TryConvertString(value) {
return IsValueToString(value) ? value.toString() : value;
}
function TryConvertNumber(value) {
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
}
function TryConvertInteger(value) {
return IsStringNumeric(value) ? parseInt(value) : IsNumber(value) ? value | 0 : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
}
function TryConvertNull(value) {
return IsString(value) && value.toLowerCase() === 'null' ? null : value;
}
function TryConvertUndefined(value) {
return IsString(value) && value === 'undefined' ? undefined : value;
}
function TryConvertDate(value) {
// note: this function may return an invalid dates for the regex tests
// above. Invalid dates will however be checked during the casting
// function and will return a epoch date if invalid. Consider better
// string parsing for the iso dates in future revisions.
return IsDate(value)
? value
: IsNumber(value)
? new globalThis.Date(value)
: IsValueTrue(value)
? new globalThis.Date(1)
: IsValueFalse(value)
? new globalThis.Date(0)
: IsStringNumeric(value)
? new globalThis.Date(parseInt(value))
: IsTimeStringWithoutTimeZone(value)
? new globalThis.Date(`1970-01-01T${value}.000Z`)
: IsTimeStringWithTimeZone(value)
? new globalThis.Date(`1970-01-01T${value}`)
: IsDateTimeStringWithoutTimeZone(value)
? new globalThis.Date(`${value}.000Z`)
: IsDateTimeStringWithTimeZone(value)
? new globalThis.Date(value)
: IsDateString(value)
? new globalThis.Date(`${value}T00:00:00.000Z`)
: value;
}
// ----------------------------------------------------------------------------------------------
// Cast
// ----------------------------------------------------------------------------------------------
function Any(schema, references, value) {
return value;
}
function Array(schema, references, value) {
if (IsArray(value)) {
return value.map((value) => Visit(schema.items, references, value));
}
return value;
}
function BigInt(schema, references, value) {
return TryConvertBigInt(value);
}
function Boolean(schema, references, value) {
return TryConvertBoolean(value);
}
function Constructor(schema, references, value) {
return clone_1.ValueClone.Clone(value);
}
function Date(schema, references, value) {
return TryConvertDate(value);
}
function Function(schema, references, value) {
return value;
}
function Integer(schema, references, value) {
return TryConvertInteger(value);
}
function Intersect(schema, references, value) {
return value;
}
function Literal(schema, references, value) {
return TryConvertLiteral(schema, value);
}
function Never(schema, references, value) {
return value;
}
function Null(schema, references, value) {
return TryConvertNull(value);
}
function Number(schema, references, value) {
return TryConvertNumber(value);
}
function Object(schema, references, value) {
if (IsObject(value))
return globalThis.Object.keys(schema.properties).reduce((acc, key) => {
return value[key] !== undefined ? { ...acc, [key]: Visit(schema.properties[key], references, value[key]) } : { ...acc };
}, value);
return value;
}
function Promise(schema, references, value) {
return value;
}
function Record(schema, references, value) {
const propertyKey = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
const property = schema.patternProperties[propertyKey];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(property, references, propValue);
}
return result;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueConvertDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
return TryConvertString(value);
}
function Symbol(schema, references, value) {
return value;
}
function TemplateLiteral(schema, references, value) {
return value;
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueConvertDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (IsArray(value) && schema.items !== undefined) {
return value.map((value, index) => {
return index < schema.items.length ? Visit(schema.items[index], references, value) : value;
});
}
return value;
}
function Undefined(schema, references, value) {
return TryConvertUndefined(value);
}
function Union(schema, references, value) {
for (const subschema of schema.anyOf) {
const converted = Visit(subschema, references, value);
if (check_1.ValueCheck.Check(subschema, references, converted)) {
return converted;
}
}
return value;
}
function Uint8Array(schema, references, value) {
return value;
}
function Unknown(schema, references, value) {
return value;
}
function Void(schema, references, value) {
return value;
}
function UserDefined(schema, references, value) {
return value;
}
function Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueConvertUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
ValueConvert.Visit = Visit;
function Convert(schema, references, value) {
return Visit(schema, references, clone_1.ValueClone.Clone(value));
}
ValueConvert.Convert = Convert;
})(ValueConvert = exports.ValueConvert || (exports.ValueConvert = {}));

View file

@ -0,0 +1,26 @@
import * as Types from '../typebox';
export declare class ValueCreateUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateNeverTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateIntersectTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateTempateLiteralTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema: Types.TSchema, references: Types.TSchema[]): unknown;
function Create<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
}

View file

@ -0,0 +1,480 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCreate = exports.ValueCreateDereferenceError = exports.ValueCreateTempateLiteralTypeError = exports.ValueCreateIntersectTypeError = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
const Types = require("../typebox");
const check_1 = require("./check");
// --------------------------------------------------------------------------
// Errors
// --------------------------------------------------------------------------
class ValueCreateUnknownTypeError extends Error {
constructor(schema) {
super('ValueCreate: Unknown type');
this.schema = schema;
}
}
exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError;
class ValueCreateNeverTypeError extends Error {
constructor(schema) {
super('ValueCreate: Never types cannot be created');
this.schema = schema;
}
}
exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError;
class ValueCreateIntersectTypeError extends Error {
constructor(schema) {
super('ValueCreate: Intersect produced invalid value. Consider using a default value.');
this.schema = schema;
}
}
exports.ValueCreateIntersectTypeError = ValueCreateIntersectTypeError;
class ValueCreateTempateLiteralTypeError extends Error {
constructor(schema) {
super('ValueCreate: Can only create template literal values from patterns that produce finite sequences. Consider using a default value.');
this.schema = schema;
}
}
exports.ValueCreateTempateLiteralTypeError = ValueCreateTempateLiteralTypeError;
class ValueCreateDereferenceError extends Error {
constructor(schema) {
super(`ValueCreate: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCreateDereferenceError = ValueCreateDereferenceError;
// --------------------------------------------------------------------------
// ValueCreate
// --------------------------------------------------------------------------
var ValueCreate;
(function (ValueCreate) {
// --------------------------------------------------------
// Guards
// --------------------------------------------------------
function IsString(value) {
return typeof value === 'string';
}
// --------------------------------------------------------
// Types
// --------------------------------------------------------
function Any(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return {};
}
}
function Array(schema, references) {
if (schema.uniqueItems === true && schema.default === undefined) {
throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value');
}
else if ('default' in schema) {
return schema.default;
}
else if (schema.minItems !== undefined) {
return globalThis.Array.from({ length: schema.minItems }).map((item) => {
return ValueCreate.Create(schema.items, references);
});
}
else {
return [];
}
}
function BigInt(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return globalThis.BigInt(0);
}
}
function Boolean(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return false;
}
}
function Constructor(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const value = ValueCreate.Create(schema.returns, references);
if (typeof value === 'object' && !globalThis.Array.isArray(value)) {
return class {
constructor() {
for (const [key, val] of globalThis.Object.entries(value)) {
const self = this;
self[key] = val;
}
}
};
}
else {
return class {
};
}
}
}
function Date(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimumTimestamp !== undefined) {
return new globalThis.Date(schema.minimumTimestamp);
}
else {
return new globalThis.Date(0);
}
}
function Function(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return () => ValueCreate.Create(schema.returns, references);
}
}
function Integer(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Intersect(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
// Note: The best we can do here is attempt to instance each sub type and apply through object assign. For non-object
// sub types, we just escape the assignment and just return the value. In the latter case, this is typically going to
// be a consequence of an illogical intersection.
const value = schema.allOf.reduce((acc, schema) => {
const next = Visit(schema, references);
return typeof next === 'object' ? { ...acc, ...next } : next;
}, {});
if (!check_1.ValueCheck.Check(schema, references, value))
throw new ValueCreateIntersectTypeError(schema);
return value;
}
}
function Literal(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return schema.const;
}
}
function Never(schema, references) {
throw new ValueCreateNeverTypeError(schema);
}
function Not(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return Visit(schema.allOf[1], references);
}
}
function Null(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return null;
}
}
function Number(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Object(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const required = new Set(schema.required);
return (schema.default ||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc };
}, {}));
}
}
function Promise(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references));
}
}
function Record(schema, references) {
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
if ('default' in schema) {
return schema.default;
}
else if (!(keyPattern === Types.PatternStringExact || keyPattern === Types.PatternNumberExact)) {
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema, references) };
}, {});
}
else {
return {};
}
}
function Ref(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
if (index === -1)
throw new ValueCreateDereferenceError(schema);
const target = references[index];
return Visit(target, references);
}
}
function String(schema, references) {
if (schema.pattern !== undefined) {
if (!('default' in schema)) {
throw new Error('ValueCreate.String: String types with patterns must specify a default value');
}
else {
return schema.default;
}
}
else if (schema.format !== undefined) {
if (!('default' in schema)) {
throw new Error('ValueCreate.String: String types with formats must specify a default value');
}
else {
return schema.default;
}
}
else {
if ('default' in schema) {
return schema.default;
}
else if (schema.minLength !== undefined) {
return globalThis.Array.from({ length: schema.minLength })
.map(() => '.')
.join('');
}
else {
return '';
}
}
}
function Symbol(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if ('value' in schema) {
return globalThis.Symbol.for(schema.value);
}
else {
return globalThis.Symbol();
}
}
function TemplateLiteral(schema, references) {
if ('default' in schema) {
return schema.default;
}
const expression = Types.TemplateLiteralParser.ParseExact(schema.pattern);
if (!Types.TemplateLiteralFinite.Check(expression))
throw new ValueCreateTempateLiteralTypeError(schema);
const sequence = Types.TemplateLiteralGenerator.Generate(expression);
return sequence.next().value;
}
function This(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
if (index === -1)
throw new ValueCreateDereferenceError(schema);
const target = references[index];
return Visit(target, references);
}
}
function Tuple(schema, references) {
if ('default' in schema) {
return schema.default;
}
if (schema.items === undefined) {
return [];
}
else {
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references));
}
}
function Undefined(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return undefined;
}
}
function Union(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Union: Cannot create Union with zero variants');
}
else {
return ValueCreate.Create(schema.anyOf[0], references);
}
}
function Uint8Array(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minByteLength !== undefined) {
return new globalThis.Uint8Array(schema.minByteLength);
}
else {
return new globalThis.Uint8Array(0);
}
}
function Unknown(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return {};
}
}
function Void(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return void 0;
}
}
function UserDefined(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
throw new Error('ValueCreate.UserDefined: User defined types must specify a default value');
}
}
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema, references) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return Any(schema_, references_);
case 'Array':
return Array(schema_, references_);
case 'BigInt':
return BigInt(schema_, references_);
case 'Boolean':
return Boolean(schema_, references_);
case 'Constructor':
return Constructor(schema_, references_);
case 'Date':
return Date(schema_, references_);
case 'Function':
return Function(schema_, references_);
case 'Integer':
return Integer(schema_, references_);
case 'Intersect':
return Intersect(schema_, references_);
case 'Literal':
return Literal(schema_, references_);
case 'Never':
return Never(schema_, references_);
case 'Not':
return Not(schema_, references_);
case 'Null':
return Null(schema_, references_);
case 'Number':
return Number(schema_, references_);
case 'Object':
return Object(schema_, references_);
case 'Promise':
return Promise(schema_, references_);
case 'Record':
return Record(schema_, references_);
case 'Ref':
return Ref(schema_, references_);
case 'String':
return String(schema_, references_);
case 'Symbol':
return Symbol(schema_, references_);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_);
case 'This':
return This(schema_, references_);
case 'Tuple':
return Tuple(schema_, references_);
case 'Undefined':
return Undefined(schema_, references_);
case 'Union':
return Union(schema_, references_);
case 'Uint8Array':
return Uint8Array(schema_, references_);
case 'Unknown':
return Unknown(schema_, references_);
case 'Void':
return Void(schema_, references_);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCreateUnknownTypeError(schema_);
return UserDefined(schema_, references_);
}
}
ValueCreate.Visit = Visit;
function Create(schema, references) {
return Visit(schema, references);
}
ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));

View file

@ -0,0 +1,43 @@
import { Static } from '../typebox';
export type Insert = Static<typeof Insert>;
export declare const Insert: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"insert">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>;
export type Update = Static<typeof Update>;
export declare const Update: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"update">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>;
export type Delete = Static<typeof Delete>;
export declare const Delete: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"delete">;
path: import("../typebox").TString<string>;
}>;
export type Edit = Static<typeof Edit>;
export declare const Edit: import("../typebox").TUnion<[import("../typebox").TObject<{
type: import("../typebox").TLiteral<"insert">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>, import("../typebox").TObject<{
type: import("../typebox").TLiteral<"update">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>, import("../typebox").TObject<{
type: import("../typebox").TLiteral<"delete">;
path: import("../typebox").TString<string>;
}>]>;
export declare class ValueDeltaObjectWithSymbolKeyError extends Error {
readonly key: unknown;
constructor(key: unknown);
}
export declare class ValueDeltaUnableToDiffUnknownValue extends Error {
readonly value: unknown;
constructor(value: unknown);
}
export declare namespace ValueDelta {
function Diff(current: unknown, next: unknown): Edit[];
function Patch<T = any>(current: unknown, edits: Edit[]): T;
}

View file

@ -0,0 +1,204 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueDelta = exports.ValueDeltaUnableToDiffUnknownValue = exports.ValueDeltaObjectWithSymbolKeyError = exports.Edit = exports.Delete = exports.Update = exports.Insert = void 0;
const typebox_1 = require("../typebox");
const is_1 = require("./is");
const clone_1 = require("./clone");
const pointer_1 = require("./pointer");
exports.Insert = typebox_1.Type.Object({
type: typebox_1.Type.Literal('insert'),
path: typebox_1.Type.String(),
value: typebox_1.Type.Unknown(),
});
exports.Update = typebox_1.Type.Object({
type: typebox_1.Type.Literal('update'),
path: typebox_1.Type.String(),
value: typebox_1.Type.Unknown(),
});
exports.Delete = typebox_1.Type.Object({
type: typebox_1.Type.Literal('delete'),
path: typebox_1.Type.String(),
});
exports.Edit = typebox_1.Type.Union([exports.Insert, exports.Update, exports.Delete]);
// ---------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------
class ValueDeltaObjectWithSymbolKeyError extends Error {
constructor(key) {
super('ValueDelta: Cannot diff objects with symbol keys');
this.key = key;
}
}
exports.ValueDeltaObjectWithSymbolKeyError = ValueDeltaObjectWithSymbolKeyError;
class ValueDeltaUnableToDiffUnknownValue extends Error {
constructor(value) {
super('ValueDelta: Unable to create diff edits for unknown value');
this.value = value;
}
}
exports.ValueDeltaUnableToDiffUnknownValue = ValueDeltaUnableToDiffUnknownValue;
// ---------------------------------------------------------------------
// ValueDelta
// ---------------------------------------------------------------------
var ValueDelta;
(function (ValueDelta) {
// ---------------------------------------------------------------------
// Edits
// ---------------------------------------------------------------------
function Update(path, value) {
return { type: 'update', path, value };
}
function Insert(path, value) {
return { type: 'insert', path, value };
}
function Delete(path) {
return { type: 'delete', path };
}
// ---------------------------------------------------------------------
// Diff
// ---------------------------------------------------------------------
function* Object(path, current, next) {
if (!is_1.Is.Object(next))
return yield Update(path, next);
const currentKeys = [...globalThis.Object.keys(current), ...globalThis.Object.getOwnPropertySymbols(current)];
const nextKeys = [...globalThis.Object.keys(next), ...globalThis.Object.getOwnPropertySymbols(next)];
for (const key of currentKeys) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (next[key] === undefined && nextKeys.includes(key))
yield Update(`${path}/${String(key)}`, undefined);
}
for (const key of nextKeys) {
if (current[key] === undefined || next[key] === undefined)
continue;
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
yield* Visit(`${path}/${String(key)}`, current[key], next[key]);
}
for (const key of nextKeys) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (current[key] === undefined)
yield Insert(`${path}/${String(key)}`, next[key]);
}
for (const key of currentKeys.reverse()) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (next[key] === undefined && !nextKeys.includes(key))
yield Delete(`${path}/${String(key)}`);
}
}
function* Array(path, current, next) {
if (!is_1.Is.Array(next))
return yield Update(path, next);
for (let i = 0; i < Math.min(current.length, next.length); i++) {
yield* Visit(`${path}/${i}`, current[i], next[i]);
}
for (let i = 0; i < next.length; i++) {
if (i < current.length)
continue;
yield Insert(`${path}/${i}`, next[i]);
}
for (let i = current.length - 1; i >= 0; i--) {
if (i < next.length)
continue;
yield Delete(`${path}/${i}`);
}
}
function* TypedArray(path, current, next) {
if (!is_1.Is.TypedArray(next) || current.length !== next.length || globalThis.Object.getPrototypeOf(current).constructor.name !== globalThis.Object.getPrototypeOf(next).constructor.name)
return yield Update(path, next);
for (let i = 0; i < Math.min(current.length, next.length); i++) {
yield* Visit(`${path}/${i}`, current[i], next[i]);
}
}
function* Value(path, current, next) {
if (current === next)
return;
yield Update(path, next);
}
function* Visit(path, current, next) {
if (is_1.Is.Object(current)) {
return yield* Object(path, current, next);
}
else if (is_1.Is.Array(current)) {
return yield* Array(path, current, next);
}
else if (is_1.Is.TypedArray(current)) {
return yield* TypedArray(path, current, next);
}
else if (is_1.Is.Value(current)) {
return yield* Value(path, current, next);
}
else {
throw new ValueDeltaUnableToDiffUnknownValue(current);
}
}
function Diff(current, next) {
return [...Visit('', current, next)];
}
ValueDelta.Diff = Diff;
// ---------------------------------------------------------------------
// Patch
// ---------------------------------------------------------------------
function IsRootUpdate(edits) {
return edits.length > 0 && edits[0].path === '' && edits[0].type === 'update';
}
function IsIdentity(edits) {
return edits.length === 0;
}
function Patch(current, edits) {
if (IsRootUpdate(edits)) {
return clone_1.ValueClone.Clone(edits[0].value);
}
if (IsIdentity(edits)) {
return clone_1.ValueClone.Clone(current);
}
const clone = clone_1.ValueClone.Clone(current);
for (const edit of edits) {
switch (edit.type) {
case 'insert': {
pointer_1.ValuePointer.Set(clone, edit.path, edit.value);
break;
}
case 'update': {
pointer_1.ValuePointer.Set(clone, edit.path, edit.value);
break;
}
case 'delete': {
pointer_1.ValuePointer.Delete(clone, edit.path);
break;
}
}
}
return clone;
}
ValueDelta.Patch = Patch;
})(ValueDelta = exports.ValueDelta || (exports.ValueDelta = {}));

View file

@ -0,0 +1,3 @@
export declare namespace ValueEqual {
function Equal<T>(left: T, right: unknown): right is T;
}

View file

@ -0,0 +1,80 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueEqual = void 0;
const is_1 = require("./is");
var ValueEqual;
(function (ValueEqual) {
function Object(left, right) {
if (!is_1.Is.Object(right))
return false;
const leftKeys = [...globalThis.Object.keys(left), ...globalThis.Object.getOwnPropertySymbols(left)];
const rightKeys = [...globalThis.Object.keys(right), ...globalThis.Object.getOwnPropertySymbols(right)];
if (leftKeys.length !== rightKeys.length)
return false;
return leftKeys.every((key) => Equal(left[key], right[key]));
}
function Date(left, right) {
return is_1.Is.Date(right) && left.getTime() === right.getTime();
}
function Array(left, right) {
if (!is_1.Is.Array(right) || left.length !== right.length)
return false;
return left.every((value, index) => Equal(value, right[index]));
}
function TypedArray(left, right) {
if (!is_1.Is.TypedArray(right) || left.length !== right.length || globalThis.Object.getPrototypeOf(left).constructor.name !== globalThis.Object.getPrototypeOf(right).constructor.name)
return false;
return left.every((value, index) => Equal(value, right[index]));
}
function Value(left, right) {
return left === right;
}
function Equal(left, right) {
if (is_1.Is.Object(left)) {
return Object(left, right);
}
else if (is_1.Is.Date(left)) {
return Date(left, right);
}
else if (is_1.Is.TypedArray(left)) {
return TypedArray(left, right);
}
else if (is_1.Is.Array(left)) {
return Array(left, right);
}
else if (is_1.Is.Value(left)) {
return Value(left, right);
}
else {
throw new Error('ValueEquals: Unable to compare value');
}
}
ValueEqual.Equal = Equal;
})(ValueEqual = exports.ValueEqual || (exports.ValueEqual = {}));

View file

@ -0,0 +1,8 @@
export declare class ValueHashError extends Error {
readonly value: unknown;
constructor(value: unknown);
}
export declare namespace ValueHash {
/** Creates a FNV1A-64 non cryptographic hash of the given value */
function Create(value: unknown): bigint;
}

View file

@ -0,0 +1,208 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/hash
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueHash = exports.ValueHashError = void 0;
class ValueHashError extends Error {
constructor(value) {
super(`Hash: Unable to hash value`);
this.value = value;
}
}
exports.ValueHashError = ValueHashError;
var ValueHash;
(function (ValueHash) {
let ByteMarker;
(function (ByteMarker) {
ByteMarker[ByteMarker["Undefined"] = 0] = "Undefined";
ByteMarker[ByteMarker["Null"] = 1] = "Null";
ByteMarker[ByteMarker["Boolean"] = 2] = "Boolean";
ByteMarker[ByteMarker["Number"] = 3] = "Number";
ByteMarker[ByteMarker["String"] = 4] = "String";
ByteMarker[ByteMarker["Object"] = 5] = "Object";
ByteMarker[ByteMarker["Array"] = 6] = "Array";
ByteMarker[ByteMarker["Date"] = 7] = "Date";
ByteMarker[ByteMarker["Uint8Array"] = 8] = "Uint8Array";
ByteMarker[ByteMarker["Symbol"] = 9] = "Symbol";
ByteMarker[ByteMarker["BigInt"] = 10] = "BigInt";
})(ByteMarker || (ByteMarker = {}));
// ----------------------------------------------------
// State
// ----------------------------------------------------
let Hash = globalThis.BigInt('14695981039346656037');
const [Prime, Size] = [globalThis.BigInt('1099511628211'), globalThis.BigInt('2') ** globalThis.BigInt('64')];
const Bytes = globalThis.Array.from({ length: 256 }).map((_, i) => globalThis.BigInt(i));
const F64 = new globalThis.Float64Array(1);
const F64In = new globalThis.DataView(F64.buffer);
const F64Out = new globalThis.Uint8Array(F64.buffer);
// ----------------------------------------------------
// Guards
// ----------------------------------------------------
function IsDate(value) {
return value instanceof globalThis.Date;
}
function IsUint8Array(value) {
return value instanceof globalThis.Uint8Array;
}
function IsArray(value) {
return globalThis.Array.isArray(value);
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsNull(value) {
return value === null;
}
function IsNumber(value) {
return typeof value === 'number';
}
function IsSymbol(value) {
return typeof value === 'symbol';
}
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsObject(value) {
return typeof value === 'object' && value !== null && !IsArray(value) && !IsDate(value) && !IsUint8Array(value);
}
function IsString(value) {
return typeof value === 'string';
}
function IsUndefined(value) {
return value === undefined;
}
// ----------------------------------------------------
// Encoding
// ----------------------------------------------------
function Array(value) {
FNV1A64(ByteMarker.Array);
for (const item of value) {
Visit(item);
}
}
function Boolean(value) {
FNV1A64(ByteMarker.Boolean);
FNV1A64(value ? 1 : 0);
}
function BigInt(value) {
FNV1A64(ByteMarker.BigInt);
F64In.setBigInt64(0, value);
for (const byte of F64Out) {
FNV1A64(byte);
}
}
function Date(value) {
FNV1A64(ByteMarker.Date);
Visit(value.getTime());
}
function Null(value) {
FNV1A64(ByteMarker.Null);
}
function Number(value) {
FNV1A64(ByteMarker.Number);
F64In.setFloat64(0, value);
for (const byte of F64Out) {
FNV1A64(byte);
}
}
function Object(value) {
FNV1A64(ByteMarker.Object);
for (const key of globalThis.Object.keys(value).sort()) {
Visit(key);
Visit(value[key]);
}
}
function String(value) {
FNV1A64(ByteMarker.String);
for (let i = 0; i < value.length; i++) {
FNV1A64(value.charCodeAt(i));
}
}
function Symbol(value) {
FNV1A64(ByteMarker.Symbol);
Visit(value.description);
}
function Uint8Array(value) {
FNV1A64(ByteMarker.Uint8Array);
for (let i = 0; i < value.length; i++) {
FNV1A64(value[i]);
}
}
function Undefined(value) {
return FNV1A64(ByteMarker.Undefined);
}
function Visit(value) {
if (IsArray(value)) {
Array(value);
}
else if (IsBoolean(value)) {
Boolean(value);
}
else if (IsBigInt(value)) {
BigInt(value);
}
else if (IsDate(value)) {
Date(value);
}
else if (IsNull(value)) {
Null(value);
}
else if (IsNumber(value)) {
Number(value);
}
else if (IsObject(value)) {
Object(value);
}
else if (IsString(value)) {
String(value);
}
else if (IsSymbol(value)) {
Symbol(value);
}
else if (IsUint8Array(value)) {
Uint8Array(value);
}
else if (IsUndefined(value)) {
Undefined(value);
}
else {
throw new ValueHashError(value);
}
}
function FNV1A64(byte) {
Hash = Hash ^ Bytes[byte];
Hash = (Hash * Prime) % Size;
}
/** Creates a FNV1A-64 non cryptographic hash of the given value */
function Create(value) {
Hash = globalThis.BigInt('14695981039346656037');
Visit(value);
return Hash;
}
ValueHash.Create = Create;
})(ValueHash = exports.ValueHash || (exports.ValueHash = {}));

View file

@ -0,0 +1,6 @@
export { ValueError, ValueErrorIterator, ValueErrorType } from '../errors/index';
export { ValueHash } from './hash';
export { Edit, Insert, Update, Delete } from './delta';
export { Mutable } from './mutate';
export * from './pointer';
export * from './value';

View file

@ -0,0 +1,56 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Delete = exports.Update = exports.Insert = exports.Edit = exports.ValueHash = exports.ValueErrorType = exports.ValueErrorIterator = void 0;
var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorIterator", { enumerable: true, get: function () { return index_1.ValueErrorIterator; } });
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
var hash_1 = require("./hash");
Object.defineProperty(exports, "ValueHash", { enumerable: true, get: function () { return hash_1.ValueHash; } });
var delta_1 = require("./delta");
Object.defineProperty(exports, "Edit", { enumerable: true, get: function () { return delta_1.Edit; } });
Object.defineProperty(exports, "Insert", { enumerable: true, get: function () { return delta_1.Insert; } });
Object.defineProperty(exports, "Update", { enumerable: true, get: function () { return delta_1.Update; } });
Object.defineProperty(exports, "Delete", { enumerable: true, get: function () { return delta_1.Delete; } });
__exportStar(require("./pointer"), exports);
__exportStar(require("./value"), exports);

View file

@ -0,0 +1,11 @@
export type ValueType = null | undefined | Function | symbol | bigint | number | boolean | string;
export type ObjectType = Record<string | number | symbol, unknown>;
export type TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
export type ArrayType = unknown[];
export declare namespace Is {
function Object(value: unknown): value is ObjectType;
function Date(value: unknown): value is Date;
function Array(value: unknown): value is ArrayType;
function Value(value: unknown): value is ValueType;
function TypedArray(value: unknown): value is TypedArrayType;
}

View file

@ -0,0 +1,53 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Is = void 0;
var Is;
(function (Is) {
function Object(value) {
return value !== null && typeof value === 'object' && !globalThis.Array.isArray(value) && !ArrayBuffer.isView(value) && !(value instanceof globalThis.Date);
}
Is.Object = Object;
function Date(value) {
return value instanceof globalThis.Date;
}
Is.Date = Date;
function Array(value) {
return globalThis.Array.isArray(value) && !ArrayBuffer.isView(value);
}
Is.Array = Array;
function Value(value) {
return value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string';
}
Is.Value = Value;
function TypedArray(value) {
return ArrayBuffer.isView(value);
}
Is.TypedArray = TypedArray;
})(Is = exports.Is || (exports.Is = {}));

View file

@ -0,0 +1,13 @@
export declare class ValueMutateTypeMismatchError extends Error {
constructor();
}
export declare class ValueMutateInvalidRootMutationError extends Error {
constructor();
}
export type Mutable = {
[key: string]: unknown;
} | unknown[];
export declare namespace ValueMutate {
/** Performs a deep mutable value assignment while retaining internal references. */
function Mutate(current: Mutable, next: Mutable): void;
}

View file

@ -0,0 +1,121 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueMutate = exports.ValueMutateInvalidRootMutationError = exports.ValueMutateTypeMismatchError = void 0;
const is_1 = require("./is");
const pointer_1 = require("./pointer");
const clone_1 = require("./clone");
class ValueMutateTypeMismatchError extends Error {
constructor() {
super('ValueMutate: Cannot assign due type mismatch of assignable values');
}
}
exports.ValueMutateTypeMismatchError = ValueMutateTypeMismatchError;
class ValueMutateInvalidRootMutationError extends Error {
constructor() {
super('ValueMutate: Only object and array types can be mutated at the root level');
}
}
exports.ValueMutateInvalidRootMutationError = ValueMutateInvalidRootMutationError;
var ValueMutate;
(function (ValueMutate) {
function Object(root, path, current, next) {
if (!is_1.Is.Object(current)) {
pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next));
}
else {
const currentKeys = globalThis.Object.keys(current);
const nextKeys = globalThis.Object.keys(next);
for (const currentKey of currentKeys) {
if (!nextKeys.includes(currentKey)) {
delete current[currentKey];
}
}
for (const nextKey of nextKeys) {
if (!currentKeys.includes(nextKey)) {
current[nextKey] = null;
}
}
for (const nextKey of nextKeys) {
Visit(root, `${path}/${nextKey}`, current[nextKey], next[nextKey]);
}
}
}
function Array(root, path, current, next) {
if (!is_1.Is.Array(current)) {
pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next));
}
else {
for (let index = 0; index < next.length; index++) {
Visit(root, `${path}/${index}`, current[index], next[index]);
}
current.splice(next.length);
}
}
function TypedArray(root, path, current, next) {
if (is_1.Is.TypedArray(current) && current.length === next.length) {
for (let i = 0; i < current.length; i++) {
current[i] = next[i];
}
}
else {
pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next));
}
}
function Value(root, path, current, next) {
if (current === next)
return;
pointer_1.ValuePointer.Set(root, path, next);
}
function Visit(root, path, current, next) {
if (is_1.Is.Array(next)) {
return Array(root, path, current, next);
}
else if (is_1.Is.TypedArray(next)) {
return TypedArray(root, path, current, next);
}
else if (is_1.Is.Object(next)) {
return Object(root, path, current, next);
}
else if (is_1.Is.Value(next)) {
return Value(root, path, current, next);
}
}
/** Performs a deep mutable value assignment while retaining internal references. */
function Mutate(current, next) {
if (is_1.Is.TypedArray(current) || is_1.Is.Value(current) || is_1.Is.TypedArray(next) || is_1.Is.Value(next)) {
throw new ValueMutateInvalidRootMutationError();
}
if ((is_1.Is.Object(current) && is_1.Is.Array(next)) || (is_1.Is.Array(current) && is_1.Is.Object(next))) {
throw new ValueMutateTypeMismatchError();
}
Visit(current, '', current, next);
}
ValueMutate.Mutate = Mutate;
})(ValueMutate = exports.ValueMutate || (exports.ValueMutate = {}));

View file

@ -0,0 +1,24 @@
export declare class ValuePointerRootSetError extends Error {
readonly value: unknown;
readonly path: string;
readonly update: unknown;
constructor(value: unknown, path: string, update: unknown);
}
export declare class ValuePointerRootDeleteError extends Error {
readonly value: unknown;
readonly path: string;
constructor(value: unknown, path: string);
}
/** Provides functionality to update values through RFC6901 string pointers */
export declare namespace ValuePointer {
/** Formats the given pointer into navigable key components */
function Format(pointer: string): IterableIterator<string>;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value: any, pointer: string, update: unknown): void;
/** Deletes a value at the given pointer */
function Delete(value: any, pointer: string): void;
/** Returns true if a value exists at the given pointer */
function Has(value: any, pointer: string): boolean;
/** Gets the value at the given pointer */
function Get(value: any, pointer: string): any;
}

View file

@ -0,0 +1,142 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0;
class ValuePointerRootSetError extends Error {
constructor(value, path, update) {
super('ValuePointer: Cannot set root value');
this.value = value;
this.path = path;
this.update = update;
}
}
exports.ValuePointerRootSetError = ValuePointerRootSetError;
class ValuePointerRootDeleteError extends Error {
constructor(value, path) {
super('ValuePointer: Cannot delete root value');
this.value = value;
this.path = path;
}
}
exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError;
/** Provides functionality to update values through RFC6901 string pointers */
var ValuePointer;
(function (ValuePointer) {
function Escape(component) {
return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~');
}
/** Formats the given pointer into navigable key components */
function* Format(pointer) {
if (pointer === '')
return;
let [start, end] = [0, 0];
for (let i = 0; i < pointer.length; i++) {
const char = pointer.charAt(i);
if (char === '/') {
if (i === 0) {
start = i + 1;
}
else {
end = i;
yield Escape(pointer.slice(start, end));
start = i + 1;
}
}
else {
end = i;
}
}
yield Escape(pointer.slice(start));
}
ValuePointer.Format = Format;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value, pointer, update) {
if (pointer === '')
throw new ValuePointerRootSetError(value, pointer, update);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
next[component] = {};
owner = next;
next = next[component];
key = component;
}
owner[key] = update;
}
ValuePointer.Set = Set;
/** Deletes a value at the given pointer */
function Delete(value, pointer) {
if (pointer === '')
throw new ValuePointerRootDeleteError(value, pointer);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined || next[component] === null)
return;
owner = next;
next = next[component];
key = component;
}
if (globalThis.Array.isArray(owner)) {
const index = parseInt(key);
owner.splice(index, 1);
}
else {
delete owner[key];
}
}
ValuePointer.Delete = Delete;
/** Returns true if a value exists at the given pointer */
function Has(value, pointer) {
if (pointer === '')
return true;
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
return false;
owner = next;
next = next[component];
key = component;
}
return globalThis.Object.getOwnPropertyNames(owner).includes(key);
}
ValuePointer.Has = Has;
/** Gets the value at the given pointer */
function Get(value, pointer) {
if (pointer === '')
return value;
let current = value;
for (const component of Format(pointer)) {
if (current[component] === undefined)
return undefined;
current = current[component];
}
return current;
}
ValuePointer.Get = Get;
})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {}));

View file

@ -0,0 +1,39 @@
import * as Types from '../typebox';
import { ValueErrorIterator } from '../errors/index';
import { Mutable } from './mutate';
import { Edit } from './delta';
/** Provides functions to perform structural updates to JavaScript values */
export declare namespace Value {
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number, boolean and date values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): Types.Static<T>;
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number, boolean and date values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema>(schema: T, value: unknown): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema>(schema: T): Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): value is Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema>(schema: T, value: unknown): value is Types.Static<T>;
/** Converts any type mismatched values to their target type if a conversion is possible. */
function Convert<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): unknown;
/** Converts any type mismatched values to their target type if a conversion is possible. */
function Convert<T extends Types.TSchema>(schema: T, value: unknown): unknown;
/** Returns a structural clone of the given value */
function Clone<T>(value: T): T;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): ValueErrorIterator;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema>(schema: T, value: unknown): ValueErrorIterator;
/** Returns true if left and right values are structurally equal */
function Equal<T>(left: T, right: unknown): right is T;
/** Returns edits to transform the current value into the next value */
function Diff(current: unknown, next: unknown): Edit[];
/** Returns a FNV1A-64 non cryptographic hash of the given value */
function Hash(value: unknown): bigint;
/** Returns a new value with edits applied to the given value */
function Patch<T = any>(current: unknown, edits: Edit[]): T;
/** Performs a deep mutable value assignment while retaining internal references. */
function Mutate(current: Mutable, next: Mutable): void;
}

View file

@ -0,0 +1,99 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Value = void 0;
const index_1 = require("../errors/index");
const mutate_1 = require("./mutate");
const hash_1 = require("./hash");
const equal_1 = require("./equal");
const cast_1 = require("./cast");
const clone_1 = require("./clone");
const convert_1 = require("./convert");
const create_1 = require("./create");
const check_1 = require("./check");
const delta_1 = require("./delta");
/** Provides functions to perform structural updates to JavaScript values */
var Value;
(function (Value) {
function Cast(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return cast_1.ValueCast.Cast(schema, references, value);
}
Value.Cast = Cast;
function Create(...args) {
const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []];
return create_1.ValueCreate.Create(schema, references);
}
Value.Create = Create;
function Check(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return check_1.ValueCheck.Check(schema, references, value);
}
Value.Check = Check;
function Convert(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return convert_1.ValueConvert.Convert(schema, references, value);
}
Value.Convert = Convert;
/** Returns a structural clone of the given value */
function Clone(value) {
return clone_1.ValueClone.Clone(value);
}
Value.Clone = Clone;
function Errors(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return index_1.ValueErrors.Errors(schema, references, value);
}
Value.Errors = Errors;
/** Returns true if left and right values are structurally equal */
function Equal(left, right) {
return equal_1.ValueEqual.Equal(left, right);
}
Value.Equal = Equal;
/** Returns edits to transform the current value into the next value */
function Diff(current, next) {
return delta_1.ValueDelta.Diff(current, next);
}
Value.Diff = Diff;
/** Returns a FNV1A-64 non cryptographic hash of the given value */
function Hash(value) {
return hash_1.ValueHash.Create(value);
}
Value.Hash = Hash;
/** Returns a new value with edits applied to the given value */
function Patch(current, edits) {
return delta_1.ValueDelta.Patch(current, edits);
}
Value.Patch = Patch;
/** Performs a deep mutable value assignment while retaining internal references. */
function Mutate(current, next) {
mutate_1.ValueMutate.Mutate(current, next);
}
Value.Mutate = Mutate;
})(Value = exports.Value || (exports.Value = {}));

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
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.

View file

@ -0,0 +1,87 @@
# `@jest/utils`
This packages is a collection of utilities and helper functions
## `ErrorWithStack`
This custom error class can be useful when you need to capture the stack trace of an error and provide additional context to the error message. By default, JavaScript errors only capture the stack trace when they are thrown, but this class allows you to capture the stack trace at any point in your code by calling its constructor.
## `clearLine`
It ensures that the clearing operation is only performed when running in a terminal environment, and not when the output is redirected to a file or another non-terminal destination.
## `convertDescriptorToString`
It defines a function named `convertDescriptorToString` that takes a descriptor as input and converts it to a string based on its type. It handles various types such as functions, numbers, strings, and undefined values. If the input doesn't match any of these types, it throws an error with a descriptive message.
## `createDirectory`
It creates new directory and also allows creation of nested directories.
## `deepCyclicCopy`
The `deepCyclicCopy` function provides deep copying of JavaScript objects and arrays, including handling circular references. It offers optional customization through a `DeepCyclicCopyOptions` parameter, allowing users to blacklist properties and preserve object prototypes. The function returns a completely independent deep copy of the input data structure.
## `formatTime`
This function is useful for formatting time values with appropriate SI unit prefixes for readability. It expresses time in various units (e.g., milliseconds, microseconds, nanoseconds) while ensuring the formatting is consistent and human-readable.
## `globsToMatcher`
The code efficiently converts a list of glob patterns into a reusable function for matching paths against those patterns, considering negated patterns and optimizing for performance.
## `installCommonGlobals`
Sets up various global variables and functions needed by the Jest testing framework. It ensures that these globals are properly set up for testing scenarios while maintaining compatibility with the environment's global object.
## `interopRequireDefault`
Provides a way to ensure compatibility between ES modules and CommonJS modules by handling the default export behavior appropriately.
## `invariant`
It is a utility used for asserting that a given condition is true. It's often used as a debugging aid during development to catch situations where an expected condition is not met.
## `isInteractive`
Checks whether the current environment is suitable for interactive terminal interactions.
## `isNonNullable`
Used to narrow down the type of a variable within a TypeScript code block, ensuring that it is safe to assume that the value is non-nullable. This can help avoid runtime errors related to null or undefined values.
## `isPromise`
It helps in order to determine whether a given value conforms to the structure of a Promise-like object, which typically has a `then` method. This can be useful when working with asynchronous code to ensure dealing with promises correctly.
## `pluralize`
This function is used to easily generate grammatically correct phrases in text output that depend on the count of items. It ensures that the word is correctly pluralized when needed.
## `preRunMessage`
These functions are intended for use in interactive command-line tools or scripts which provide informative messages to the user while ensuring a clean and responsive interface.
## `replacePathSepForGlob`
The function takes a string `path` as input and replaces backslashes ('\\') with forward slashes ('/') in the path. Used to normalize file paths to be compatible with glob patterns, ensuring consistency in path representation for different operating systems.
## `requireOrImportModule`
This function provides a unified way to load modules regardless of whether they use CommonJS or ESM syntax. It ensures that the default export is applied consistently when needed, allowing users to work with modules that might use different module systems.
## `setGlobal`
Used to set properties with specified values within a global object. It is designed to work in both browser-like and Node.js environments by accepting different types of global objects as input.
## `specialChars`
It defines constants and conditional values for handling platform-specific behaviors in a terminal environment. It determines if the current platform is Windows ('win32') and sets up constants for various symbols and terminal screen clearing escape sequences accordingly, ensuring proper display and behavior on both Windows and non-Windows operating systems.
## `testPathPatternToRegExp`
This function is used for consistency when serializing/deserializing global configurations and ensures that consistent regular expressions are produced for matching test paths.
## `tryRealpath`
Used to resolve the real path of a given path, but if the path doesn't exist or is a directory, it doesn't throw an error and returns the original path string. This can be useful for gracefully handling path resolution in scenarios where some paths might not exist or might be directories.

View file

@ -0,0 +1,28 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class ErrorWithStack extends Error {
constructor(message, callsite, stackLimit) {
// Ensure we have a large stack length so we get full details.
const originalStackLimit = Error.stackTraceLimit;
if (stackLimit) {
Error.stackTraceLimit = Math.max(stackLimit, originalStackLimit || 10);
}
super(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, callsite);
}
Error.stackTraceLimit = originalStackLimit;
}
}
exports.default = ErrorWithStack;

View file

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = clearLine;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function clearLine(stream) {
if (stream.isTTY) {
stream.write('\x1b[999D\x1b[K');
}
}

View file

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = convertDescriptorToString;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function convertDescriptorToString(descriptor) {
switch (typeof descriptor) {
case 'function':
if (descriptor.name) {
return descriptor.name;
}
break;
case 'number':
case 'undefined':
return `${descriptor}`;
case 'string':
return descriptor;
}
throw new Error(
`Invalid first argument, ${descriptor}. It must be a named class, named function, number, or string.`
);
}

View file

@ -0,0 +1,71 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = createDirectory;
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function createDirectory(path) {
try {
fs().mkdirSync(path, {
recursive: true
});
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}

View file

@ -0,0 +1,109 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = createProcessObject;
var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const BLACKLIST = new Set(['env', 'mainModule', '_events']);
const isWin32 = process.platform === 'win32';
const proto = Object.getPrototypeOf(process.env);
// The "process.env" object has a bunch of particularities: first, it does not
// directly extend from Object; second, it converts any assigned value to a
// string; and third, it is case-insensitive in Windows. We use a proxy here to
// mimic it (see https://nodejs.org/api/process.html#process_process_env).
function createProcessEnv() {
const real = Object.create(proto);
const lookup = {};
function deletePropertyWin32(_target, key) {
for (const name in real) {
if (Object.prototype.hasOwnProperty.call(real, name)) {
if (typeof key === 'string') {
if (name.toLowerCase() === key.toLowerCase()) {
delete real[name];
delete lookup[name.toLowerCase()];
}
} else {
if (key === name) {
delete real[name];
delete lookup[name];
}
}
}
}
return true;
}
function deleteProperty(_target, key) {
delete real[key];
delete lookup[key];
return true;
}
function getProperty(_target, key) {
return real[key];
}
function getPropertyWin32(_target, key) {
if (typeof key === 'string') {
return lookup[key in proto ? key : key.toLowerCase()];
} else {
return real[key];
}
}
const proxy = new Proxy(real, {
deleteProperty: isWin32 ? deletePropertyWin32 : deleteProperty,
get: isWin32 ? getPropertyWin32 : getProperty,
set(_target, key, value) {
const strValue = `${value}`;
if (typeof key === 'string') {
lookup[key.toLowerCase()] = strValue;
}
real[key] = strValue;
return true;
}
});
return Object.assign(proxy, process.env);
}
function createProcessObject() {
const process = require('process');
const newProcess = (0, _deepCyclicCopy.default)(process, {
blacklist: BLACKLIST,
keepPrototype: true
});
try {
// This fails on Node 12, but it's already set to 'process'
newProcess[Symbol.toStringTag] = 'process';
} catch (e) {
// Make sure it's actually set instead of potentially ignoring errors
if (newProcess[Symbol.toStringTag] !== 'process') {
e.message = `Unable to set toStringTag on process. Please open up an issue at https://github.com/jestjs/jest\n\n${e.message}`;
throw e;
}
}
// Sequentially execute all constructors over the object.
let proto = process;
while ((proto = Object.getPrototypeOf(proto))) {
if (typeof proto.constructor === 'function') {
proto.constructor.call(newProcess);
}
}
newProcess.env = createProcessEnv();
newProcess.send = () => true;
Object.defineProperty(newProcess, 'domain', {
get() {
return process.domain;
}
});
return newProcess;
}

View file

@ -0,0 +1,76 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = deepCyclicCopy;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const EMPTY = new Set();
function deepCyclicCopy(
value,
options = {
blacklist: EMPTY,
keepPrototype: false
},
cycles = new WeakMap()
) {
if (typeof value !== 'object' || value === null || Buffer.isBuffer(value)) {
return value;
} else if (cycles.has(value)) {
return cycles.get(value);
} else if (Array.isArray(value)) {
return deepCyclicCopyArray(value, options, cycles);
} else {
return deepCyclicCopyObject(value, options, cycles);
}
}
function deepCyclicCopyObject(object, options, cycles) {
const newObject = options.keepPrototype
? Object.create(Object.getPrototypeOf(object))
: {};
const descriptors = Object.getOwnPropertyDescriptors(object);
cycles.set(object, newObject);
Object.keys(descriptors).forEach(key => {
if (options.blacklist && options.blacklist.has(key)) {
delete descriptors[key];
return;
}
const descriptor = descriptors[key];
if (typeof descriptor.value !== 'undefined') {
descriptor.value = deepCyclicCopy(
descriptor.value,
{
blacklist: EMPTY,
keepPrototype: options.keepPrototype
},
cycles
);
}
descriptor.configurable = true;
});
return Object.defineProperties(newObject, descriptors);
}
function deepCyclicCopyArray(array, options, cycles) {
const newArray = options.keepPrototype
? new (Object.getPrototypeOf(array).constructor)(array.length)
: [];
const length = array.length;
cycles.set(array, newArray);
for (let i = 0; i < length; i++) {
newArray[i] = deepCyclicCopy(
array[i],
{
blacklist: EMPTY,
keepPrototype: options.keepPrototype
},
cycles
);
}
return newArray;
}

View file

@ -0,0 +1,24 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = formatTime;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function formatTime(time, prefixPower = -3, padLeftLength = 0) {
const prefixes = ['n', 'μ', 'm', ''];
const prefixIndex = Math.max(
0,
Math.min(
Math.trunc(prefixPower / 3) + prefixes.length - 1,
prefixes.length - 1
)
);
return `${String(time).padStart(padLeftLength)} ${prefixes[prefixIndex]}s`;
}

View file

@ -0,0 +1,98 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = globsToMatcher;
function _picomatch() {
const data = _interopRequireDefault(require('picomatch'));
_picomatch = function () {
return data;
};
return data;
}
var _replacePathSepForGlob = _interopRequireDefault(
require('./replacePathSepForGlob')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const globsToMatchersMap = new Map();
const picomatchOptions = {
dot: true
};
/**
* Converts a list of globs into a function that matches a path against the
* globs.
*
* Every time picomatch is called, it will parse the glob strings and turn
* them into regexp instances. Instead of calling picomatch repeatedly with
* the same globs, we can use this function which will build the picomatch
* matchers ahead of time and then have an optimized path for determining
* whether an individual path matches.
*
* This function is intended to match the behavior of `micromatch()`.
*
* @example
* const isMatch = globsToMatcher(['*.js', '!*.test.js']);
* isMatch('pizza.js'); // true
* isMatch('pizza.test.js'); // false
*/
function globsToMatcher(globs) {
if (globs.length === 0) {
// Since there were no globs given, we can simply have a fast path here and
// return with a very simple function.
return () => false;
}
const matchers = globs.map(glob => {
if (!globsToMatchersMap.has(glob)) {
const isMatch = (0, _picomatch().default)(glob, picomatchOptions, true);
const matcher = {
isMatch,
// Matchers that are negated have different behavior than matchers that
// are not negated, so we need to store this information ahead of time.
negated: isMatch.state.negated || !!isMatch.state.negatedExtglob
};
globsToMatchersMap.set(glob, matcher);
}
return globsToMatchersMap.get(glob);
});
return path => {
const replacedPath = (0, _replacePathSepForGlob.default)(path);
let kept = undefined;
let negatives = 0;
for (let i = 0; i < matchers.length; i++) {
const {isMatch, negated} = matchers[i];
if (negated) {
negatives++;
}
const matched = isMatch(replacedPath);
if (!matched && negated) {
// The path was not matched, and the matcher is a negated matcher, so we
// want to omit the path. This means that the negative matcher is
// filtering the path out.
kept = false;
} else if (matched && !negated) {
// The path was matched, and the matcher is not a negated matcher, so we
// want to keep the path.
kept = true;
}
}
// If all of the globs were negative globs, then we want to include the path
// as long as it was not explicitly not kept. Otherwise only include
// the path if it was kept. This allows sets of globs that are all negated
// to allow some paths to be matched, while sets of globs that are mixed
// negated and non-negated to cause the negated matchers to only omit paths
// and not keep them.
return negatives === matchers.length ? kept !== false : !!kept;
};
}

View file

@ -0,0 +1,136 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type {Config} from '@jest/types';
import type {Global} from '@jest/types';
declare const ARROW = ' \u203A ';
declare const CLEAR: string;
export declare function clearLine(stream: NodeJS.WriteStream): void;
export declare function convertDescriptorToString(
descriptor: Global.BlockNameLike | undefined,
): string;
export declare function createDirectory(path: string): void;
export declare function deepCyclicCopy<T>(
value: T,
options?: DeepCyclicCopyOptions,
cycles?: WeakMap<any, any>,
): T;
declare type DeepCyclicCopyOptions = {
blacklist?: Set<string>;
keepPrototype?: boolean;
};
export declare class ErrorWithStack extends Error {
constructor(
message: string | undefined,
callsite: (...args: Array<any>) => unknown,
stackLimit?: number,
);
}
export declare function formatTime(
time: number,
prefixPower?: number,
padLeftLength?: number,
): string;
/**
* Converts a list of globs into a function that matches a path against the
* globs.
*
* Every time picomatch is called, it will parse the glob strings and turn
* them into regexp instances. Instead of calling picomatch repeatedly with
* the same globs, we can use this function which will build the picomatch
* matchers ahead of time and then have an optimized path for determining
* whether an individual path matches.
*
* This function is intended to match the behavior of `micromatch()`.
*
* @example
* const isMatch = globsToMatcher(['*.js', '!*.test.js']);
* isMatch('pizza.js'); // true
* isMatch('pizza.test.js'); // false
*/
export declare function globsToMatcher(globs: Array<string>): Matcher;
declare const ICONS: {
failed: string;
pending: string;
success: string;
todo: string;
};
export declare function installCommonGlobals(
globalObject: typeof globalThis,
globals: Config.ConfigGlobals,
): typeof globalThis & Config.ConfigGlobals;
export declare function interopRequireDefault(obj: any): any;
export declare function invariant(
condition: unknown,
message?: string,
): asserts condition;
export declare const isInteractive: boolean;
export declare function isNonNullable<T>(value: T): value is NonNullable<T>;
export declare function isPromise<T = unknown>(
candidate: unknown,
): candidate is PromiseLike<T>;
declare type Matcher = (str: string) => boolean;
export declare function pluralize(
word: string,
count: number,
ending?: string,
): string;
declare namespace preRunMessage {
export {print_2 as print, remove};
}
export {preRunMessage};
declare function print_2(stream: NodeJS.WriteStream): void;
declare function remove(stream: NodeJS.WriteStream): void;
export declare function replacePathSepForGlob(path: string): string;
export declare function requireOrImportModule<T>(
filePath: string,
applyInteropRequireDefault?: boolean,
): Promise<T>;
export declare function setGlobal(
globalToMutate: typeof globalThis | Global.Global,
key: string,
value: unknown,
): void;
declare namespace specialChars {
export {ARROW, ICONS, CLEAR};
}
export {specialChars};
export declare function testPathPatternToRegExp(
testPathPattern: Config.GlobalConfig['testPathPattern'],
): RegExp;
export declare function tryRealpath(path: string): string;
export {};

View file

@ -0,0 +1,199 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'ErrorWithStack', {
enumerable: true,
get: function () {
return _ErrorWithStack.default;
}
});
Object.defineProperty(exports, 'clearLine', {
enumerable: true,
get: function () {
return _clearLine.default;
}
});
Object.defineProperty(exports, 'convertDescriptorToString', {
enumerable: true,
get: function () {
return _convertDescriptorToString.default;
}
});
Object.defineProperty(exports, 'createDirectory', {
enumerable: true,
get: function () {
return _createDirectory.default;
}
});
Object.defineProperty(exports, 'deepCyclicCopy', {
enumerable: true,
get: function () {
return _deepCyclicCopy.default;
}
});
Object.defineProperty(exports, 'formatTime', {
enumerable: true,
get: function () {
return _formatTime.default;
}
});
Object.defineProperty(exports, 'globsToMatcher', {
enumerable: true,
get: function () {
return _globsToMatcher.default;
}
});
Object.defineProperty(exports, 'installCommonGlobals', {
enumerable: true,
get: function () {
return _installCommonGlobals.default;
}
});
Object.defineProperty(exports, 'interopRequireDefault', {
enumerable: true,
get: function () {
return _interopRequireDefault.default;
}
});
Object.defineProperty(exports, 'invariant', {
enumerable: true,
get: function () {
return _invariant.default;
}
});
Object.defineProperty(exports, 'isInteractive', {
enumerable: true,
get: function () {
return _isInteractive.default;
}
});
Object.defineProperty(exports, 'isNonNullable', {
enumerable: true,
get: function () {
return _isNonNullable.default;
}
});
Object.defineProperty(exports, 'isPromise', {
enumerable: true,
get: function () {
return _isPromise.default;
}
});
Object.defineProperty(exports, 'pluralize', {
enumerable: true,
get: function () {
return _pluralize.default;
}
});
exports.preRunMessage = void 0;
Object.defineProperty(exports, 'replacePathSepForGlob', {
enumerable: true,
get: function () {
return _replacePathSepForGlob.default;
}
});
Object.defineProperty(exports, 'requireOrImportModule', {
enumerable: true,
get: function () {
return _requireOrImportModule.default;
}
});
Object.defineProperty(exports, 'setGlobal', {
enumerable: true,
get: function () {
return _setGlobal.default;
}
});
exports.specialChars = void 0;
Object.defineProperty(exports, 'testPathPatternToRegExp', {
enumerable: true,
get: function () {
return _testPathPatternToRegExp.default;
}
});
Object.defineProperty(exports, 'tryRealpath', {
enumerable: true,
get: function () {
return _tryRealpath.default;
}
});
var preRunMessage = _interopRequireWildcard(require('./preRunMessage'));
exports.preRunMessage = preRunMessage;
var specialChars = _interopRequireWildcard(require('./specialChars'));
exports.specialChars = specialChars;
var _clearLine = _interopRequireDefault2(require('./clearLine'));
var _createDirectory = _interopRequireDefault2(require('./createDirectory'));
var _ErrorWithStack = _interopRequireDefault2(require('./ErrorWithStack'));
var _installCommonGlobals = _interopRequireDefault2(
require('./installCommonGlobals')
);
var _interopRequireDefault = _interopRequireDefault2(
require('./interopRequireDefault')
);
var _isInteractive = _interopRequireDefault2(require('./isInteractive'));
var _isPromise = _interopRequireDefault2(require('./isPromise'));
var _setGlobal = _interopRequireDefault2(require('./setGlobal'));
var _deepCyclicCopy = _interopRequireDefault2(require('./deepCyclicCopy'));
var _convertDescriptorToString = _interopRequireDefault2(
require('./convertDescriptorToString')
);
var _replacePathSepForGlob = _interopRequireDefault2(
require('./replacePathSepForGlob')
);
var _testPathPatternToRegExp = _interopRequireDefault2(
require('./testPathPatternToRegExp')
);
var _globsToMatcher = _interopRequireDefault2(require('./globsToMatcher'));
var _pluralize = _interopRequireDefault2(require('./pluralize'));
var _formatTime = _interopRequireDefault2(require('./formatTime'));
var _tryRealpath = _interopRequireDefault2(require('./tryRealpath'));
var _requireOrImportModule = _interopRequireDefault2(
require('./requireOrImportModule')
);
var _invariant = _interopRequireDefault2(require('./invariant'));
var _isNonNullable = _interopRequireDefault2(require('./isNonNullable'));
function _interopRequireDefault2(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}

View file

@ -0,0 +1,115 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = installCommonGlobals;
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
var _createProcessObject = _interopRequireDefault(
require('./createProcessObject')
);
var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const DTRACE = Object.keys(globalThis).filter(key => key.startsWith('DTRACE'));
function installCommonGlobals(globalObject, globals) {
globalObject.process = (0, _createProcessObject.default)();
const symbol = globalObject.Symbol;
// Keep a reference to some globals that Jest needs
Object.defineProperties(globalObject, {
[symbol.for('jest-native-promise')]: {
enumerable: false,
value: Promise,
writable: false
},
[symbol.for('jest-native-now')]: {
enumerable: false,
value: globalObject.Date.now.bind(globalObject.Date),
writable: false
},
[symbol.for('jest-native-read-file')]: {
enumerable: false,
value: fs().readFileSync.bind(fs()),
writable: false
},
[symbol.for('jest-native-write-file')]: {
enumerable: false,
value: fs().writeFileSync.bind(fs()),
writable: false
},
[symbol.for('jest-native-exists-file')]: {
enumerable: false,
value: fs().existsSync.bind(fs()),
writable: false
},
'jest-symbol-do-not-touch': {
enumerable: false,
value: symbol,
writable: false
}
});
// Forward some APIs.
DTRACE.forEach(dtrace => {
// @ts-expect-error: no index
globalObject[dtrace] = function (...args) {
// @ts-expect-error: no index
return globalThis[dtrace].apply(this, args);
};
});
return Object.assign(globalObject, (0, _deepCyclicCopy.default)(globals));
}

View file

@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = interopRequireDefault;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// copied from https://github.com/babel/babel/blob/56044c7851d583d498f919e9546caddf8f80a72f/packages/babel-helpers/src/helpers.js#L558-L562
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj
};
}

View file

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = invariant;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function invariant(condition, message = '') {
if (!condition) {
throw new Error(message);
}
}

View file

@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _ciInfo() {
const data = require('ci-info');
_ciInfo = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var _default =
!!process.stdout.isTTY && process.env.TERM !== 'dumb' && !_ciInfo().isCI;
exports.default = _default;

View file

@ -0,0 +1,16 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = isNonNullable;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function isNonNullable(value) {
return value != null;
}

View file

@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = isPromise;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function isPromise(candidate) {
return (
candidate != null &&
(typeof candidate === 'object' || typeof candidate === 'function') &&
typeof candidate.then === 'function'
);
}

View file

@ -0,0 +1,16 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = pluralize;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function pluralize(word, count, ending = 's') {
return `${count} ${word}${count === 1 ? '' : ending}`;
}

View file

@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.print = print;
exports.remove = remove;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
var _clearLine = _interopRequireDefault(require('./clearLine'));
var _isInteractive = _interopRequireDefault(require('./isInteractive'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function print(stream) {
if (_isInteractive.default) {
stream.write(
_chalk().default.bold.dim('Determining test suites to run...')
);
}
}
function remove(stream) {
if (_isInteractive.default) {
(0, _clearLine.default)(stream);
}
}

View file

@ -0,0 +1,16 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = replacePathSepForGlob;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function replacePathSepForGlob(path) {
return path.replace(/\\(?![{}()+?.^$])/g, '/');
}

View file

@ -0,0 +1,77 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = requireOrImportModule;
function _path() {
const data = require('path');
_path = function () {
return data;
};
return data;
}
function _url() {
const data = require('url');
_url = function () {
return data;
};
return data;
}
var _interopRequireDefault = _interopRequireDefault2(
require('./interopRequireDefault')
);
function _interopRequireDefault2(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
async function requireOrImportModule(
filePath,
applyInteropRequireDefault = true
) {
if (!(0, _path().isAbsolute)(filePath) && filePath[0] === '.') {
throw new Error(
`Jest: requireOrImportModule path must be absolute, was "${filePath}"`
);
}
try {
const requiredModule = require(filePath);
if (!applyInteropRequireDefault) {
return requiredModule;
}
return (0, _interopRequireDefault.default)(requiredModule).default;
} catch (error) {
if (error.code === 'ERR_REQUIRE_ESM') {
try {
const moduleUrl = (0, _url().pathToFileURL)(filePath);
// node `import()` supports URL, but TypeScript doesn't know that
const importedModule = await import(moduleUrl.href);
if (!applyInteropRequireDefault) {
return importedModule;
}
if (!importedModule.default) {
throw new Error(
`Jest: Failed to load ESM at ${filePath} - did you use a default export?`
);
}
return importedModule.default;
} catch (innerError) {
if (innerError.message === 'Not supported') {
throw new Error(
`Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${filePath}`
);
}
throw innerError;
}
} else {
throw error;
}
}
}

View file

@ -0,0 +1,17 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = setGlobal;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function setGlobal(globalToMutate, key, value) {
// @ts-expect-error: no index
globalToMutate[key] = value;
}

View file

@ -0,0 +1,25 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.ICONS = exports.CLEAR = exports.ARROW = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const isWindows = process.platform === 'win32';
const ARROW = ' \u203A ';
exports.ARROW = ARROW;
const ICONS = {
failed: isWindows ? '\u00D7' : '\u2715',
pending: '\u25CB',
success: isWindows ? '\u221A' : '\u2713',
todo: '\u270E'
};
exports.ICONS = ICONS;
const CLEAR = isWindows ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H';
exports.CLEAR = CLEAR;

View file

@ -0,0 +1,19 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = testPathPatternToRegExp;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Because we serialize/deserialize globalConfig when we spawn workers,
// we can't pass regular expression. Using this shared function on both sides
// will ensure that we produce consistent regexp for testPathPattern.
function testPathPatternToRegExp(testPathPattern) {
return new RegExp(testPathPattern, 'i');
}

View file

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = tryRealpath;
function _gracefulFs() {
const data = require('graceful-fs');
_gracefulFs = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function tryRealpath(path) {
try {
path = _gracefulFs().realpathSync.native(path);
} catch (error) {
if (error.code !== 'ENOENT' && error.code !== 'EISDIR') {
throw error;
}
}
return path;
}

View file

@ -0,0 +1,38 @@
{
"name": "jest-util",
"version": "29.7.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-util"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
"chalk": "^4.0.0",
"ci-info": "^3.2.0",
"graceful-fs": "^4.2.9",
"picomatch": "^2.2.3"
},
"devDependencies": {
"@types/graceful-fs": "^4.1.3",
"@types/picomatch": "^2.2.2"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4e56991693da7cd4c3730dc3579a1dd1403ee630"
}

View file

@ -0,0 +1,136 @@
# Release history
**All notable changes to this project will be documented in this file.**
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
<details>
<summary><strong>Guiding Principles</strong></summary>
- Changelogs are for humans, not machines.
- There should be an entry for every single version.
- The same types of changes should be grouped.
- Versions and sections should be linkable.
- The latest version comes first.
- The release date of each versions is displayed.
- Mention whether you follow Semantic Versioning.
</details>
<details>
<summary><strong>Types of changes</strong></summary>
Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_):
- `Added` for new features.
- `Changed` for changes in existing functionality.
- `Deprecated` for soon-to-be removed features.
- `Removed` for now removed features.
- `Fixed` for any bug fixes.
- `Security` in case of vulnerabilities.
</details>
## 2.3.1 (2022-01-02)
### Fixed
* Fixes bug when a pattern containing an expression after the closing parenthesis (`/!(*.d).{ts,tsx}`) was incorrectly converted to regexp ([9f241ef](https://github.com/micromatch/picomatch/commit/9f241ef)).
### Changed
* Some documentation improvements ([f81d236](https://github.com/micromatch/picomatch/commit/f81d236), [421e0e7](https://github.com/micromatch/picomatch/commit/421e0e7)).
## 2.3.0 (2021-05-21)
### Fixed
* Fixes bug where file names with two dots were not being matched consistently with negation extglobs containing a star ([56083ef](https://github.com/micromatch/picomatch/commit/56083ef))
## 2.2.3 (2021-04-10)
### Fixed
* Do not skip pattern seperator for square brackets ([fb08a30](https://github.com/micromatch/picomatch/commit/fb08a30)).
* Set negatedExtGlob also if it does not span the whole pattern ([032e3f5](https://github.com/micromatch/picomatch/commit/032e3f5)).
## 2.2.2 (2020-03-21)
### Fixed
* Correctly handle parts of the pattern after parentheses in the `scan` method ([e15b920](https://github.com/micromatch/picomatch/commit/e15b920)).
## 2.2.1 (2020-01-04)
* Fixes [#49](https://github.com/micromatch/picomatch/issues/49), so that braces with no sets or ranges are now propertly treated as literals.
## 2.2.0 (2020-01-04)
* Disable fastpaths mode for the parse method ([5b8d33f](https://github.com/micromatch/picomatch/commit/5b8d33f))
* Add `tokens`, `slashes`, and `parts` to the object returned by `picomatch.scan()`.
## 2.1.0 (2019-10-31)
* add benchmarks for scan ([4793b92](https://github.com/micromatch/picomatch/commit/4793b92))
* Add eslint object-curly-spacing rule ([707c650](https://github.com/micromatch/picomatch/commit/707c650))
* Add prefer-const eslint rule ([5c7501c](https://github.com/micromatch/picomatch/commit/5c7501c))
* Add support for nonegate in scan API ([275c9b9](https://github.com/micromatch/picomatch/commit/275c9b9))
* Change lets to consts. Move root import up. ([4840625](https://github.com/micromatch/picomatch/commit/4840625))
* closes https://github.com/micromatch/picomatch/issues/21 ([766bcb0](https://github.com/micromatch/picomatch/commit/766bcb0))
* Fix "Extglobs" table in readme ([eb19da8](https://github.com/micromatch/picomatch/commit/eb19da8))
* fixes https://github.com/micromatch/picomatch/issues/20 ([9caca07](https://github.com/micromatch/picomatch/commit/9caca07))
* fixes https://github.com/micromatch/picomatch/issues/26 ([fa58f45](https://github.com/micromatch/picomatch/commit/fa58f45))
* Lint test ([d433a34](https://github.com/micromatch/picomatch/commit/d433a34))
* lint unit tests ([0159b55](https://github.com/micromatch/picomatch/commit/0159b55))
* Make scan work with noext ([6c02e03](https://github.com/micromatch/picomatch/commit/6c02e03))
* minor linting ([c2a2b87](https://github.com/micromatch/picomatch/commit/c2a2b87))
* minor parser improvements ([197671d](https://github.com/micromatch/picomatch/commit/197671d))
* remove eslint since it... ([07876fa](https://github.com/micromatch/picomatch/commit/07876fa))
* remove funding file ([8ebe96d](https://github.com/micromatch/picomatch/commit/8ebe96d))
* Remove unused funks ([cbc6d54](https://github.com/micromatch/picomatch/commit/cbc6d54))
* Run eslint during pretest, fix existing eslint findings ([0682367](https://github.com/micromatch/picomatch/commit/0682367))
* support `noparen` in scan ([3d37569](https://github.com/micromatch/picomatch/commit/3d37569))
* update changelog ([7b34e77](https://github.com/micromatch/picomatch/commit/7b34e77))
* update travis ([777f038](https://github.com/micromatch/picomatch/commit/777f038))
* Use eslint-disable-next-line instead of eslint-disable ([4e7c1fd](https://github.com/micromatch/picomatch/commit/4e7c1fd))
## 2.0.7 (2019-05-14)
* 2.0.7 ([9eb9a71](https://github.com/micromatch/picomatch/commit/9eb9a71))
* supports lookbehinds ([1f63f7e](https://github.com/micromatch/picomatch/commit/1f63f7e))
* update .verb.md file with typo change ([2741279](https://github.com/micromatch/picomatch/commit/2741279))
* fix: typo in README ([0753e44](https://github.com/micromatch/picomatch/commit/0753e44))
## 2.0.4 (2019-04-10)
### Fixed
- Readme link [fixed](https://github.com/micromatch/picomatch/pull/13/commits/a96ab3aa2b11b6861c23289964613d85563b05df) by @danez.
- `options.capture` now works as expected when fastpaths are enabled. See https://github.com/micromatch/picomatch/pull/12/commits/26aefd71f1cfaf95c37f1c1fcab68a693b037304. Thanks to @DrPizza.
## 2.0.0 (2019-04-10)
### Added
- Adds support for `options.onIgnore`. See the readme for details
- Adds support for `options.onResult`. See the readme for details
### Breaking changes
- The unixify option was renamed to `windows`
- caching and all related options and methods have been removed
## 1.0.0 (2018-11-05)
- adds `.onMatch` option
- improvements to `.scan` method
- numerous improvements and optimizations for matching and parsing
- better windows path handling
## 0.1.0 - 2017-04-13
First release.
[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-present, Jon Schlinkert.
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.

View file

@ -0,0 +1,708 @@
<h1 align="center">Picomatch</h1>
<p align="center">
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/v/picomatch.svg" alt="version">
</a>
<a href="https://github.com/micromatch/picomatch/actions?workflow=Tests">
<img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status">
</a>
<a href="https://coveralls.io/github/micromatch/picomatch">
<img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status">
</a>
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads">
</a>
</p>
<br>
<br>
<p align="center">
<strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br>
<em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em>
</p>
<br>
<br>
## Why picomatch?
* **Lightweight** - No dependencies
* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
* **Well tested** - Thousands of unit tests
See the [library comparison](#library-comparisons) to other libraries.
<br>
<br>
## Table of Contents
<details><summary> Click to expand </summary>
- [Install](#install)
- [Usage](#usage)
- [API](#api)
* [picomatch](#picomatch)
* [.test](#test)
* [.matchBase](#matchbase)
* [.isMatch](#ismatch)
* [.parse](#parse)
* [.scan](#scan)
* [.compileRe](#compilere)
* [.makeRe](#makere)
* [.toRegex](#toregex)
- [Options](#options)
* [Picomatch options](#picomatch-options)
* [Scan Options](#scan-options)
* [Options Examples](#options-examples)
- [Globbing features](#globbing-features)
* [Basic globbing](#basic-globbing)
* [Advanced globbing](#advanced-globbing)
* [Braces](#braces)
* [Matching special characters as literals](#matching-special-characters-as-literals)
- [Library Comparisons](#library-comparisons)
- [Benchmarks](#benchmarks)
- [Philosophies](#philosophies)
- [About](#about)
* [Author](#author)
* [License](#license)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
</details>
<br>
<br>
## Install
Install with [npm](https://www.npmjs.com/):
```sh
npm install --save picomatch
```
<br>
## Usage
The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
```js
const pm = require('picomatch');
const isMatch = pm('*.js');
console.log(isMatch('abcd')); //=> false
console.log(isMatch('a.js')); //=> true
console.log(isMatch('a.md')); //=> false
console.log(isMatch('a/b.js')); //=> false
```
<br>
## API
### [picomatch](lib/picomatch.js#L32)
Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.
**Params**
* `globs` **{String|Array}**: One or more glob patterns.
* `options` **{Object=}**
* `returns` **{Function=}**: Returns a matcher function.
**Example**
```js
const picomatch = require('picomatch');
// picomatch(glob[, options]);
const isMatch = picomatch('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true
```
### [.test](lib/picomatch.js#L117)
Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
**Params**
* `input` **{String}**: String to test.
* `regex` **{RegExp}**
* `returns` **{Object}**: Returns an object with matching info.
**Example**
```js
const picomatch = require('picomatch');
// picomatch.test(input, regex[, options]);
console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
```
### [.matchBase](lib/picomatch.js#L161)
Match the basename of a filepath.
**Params**
* `input` **{String}**: String to test.
* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
* `returns` **{Boolean}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.matchBase(input, glob[, options]);
console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
```
### [.isMatch](lib/picomatch.js#L183)
Returns true if **any** of the given glob `patterns` match the specified `string`.
**Params**
* **{String|Array}**: str The string to test.
* **{String|Array}**: patterns One or more glob patterns to use for matching.
* **{Object}**: See available [options](#options).
* `returns` **{Boolean}**: Returns true if any patterns match `str`
**Example**
```js
const picomatch = require('picomatch');
// picomatch.isMatch(string, patterns[, options]);
console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
```
### [.parse](lib/picomatch.js#L199)
Parse a glob pattern to create the source string for a regular expression.
**Params**
* `pattern` **{String}**
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.parse(pattern[, options]);
```
### [.scan](lib/picomatch.js#L231)
Scan a glob pattern to separate the pattern into segments.
**Params**
* `input` **{String}**: Glob pattern to scan.
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with
**Example**
```js
const picomatch = require('picomatch');
// picomatch.scan(input[, options]);
const result = picomatch.scan('!./foo/*.js');
console.log(result);
{ prefix: '!./',
input: '!./foo/*.js',
start: 3,
base: 'foo',
glob: '*.js',
isBrace: false,
isBracket: false,
isGlob: true,
isExtglob: false,
isGlobstar: false,
negated: true }
```
### [.compileRe](lib/picomatch.js#L245)
Compile a regular expression from the `state` object returned by the
[parse()](#parse) method.
**Params**
* `state` **{Object}**
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* `returns` **{RegExp}**
### [.makeRe](lib/picomatch.js#L286)
Create a regular expression from a parsed glob pattern.
**Params**
* `state` **{String}**: The object returned from the `.parse` method.
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* `returns` **{RegExp}**: Returns a regex created from the given pattern.
**Example**
```js
const picomatch = require('picomatch');
const state = picomatch.parse('*.js');
// picomatch.compileRe(state[, options]);
console.log(picomatch.compileRe(state));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.toRegex](lib/picomatch.js#L321)
Create a regular expression from the given regex source string.
**Params**
* `source` **{String}**: Regular expression source string.
* `options` **{Object}**
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.toRegex(source[, options]);
const { output } = picomatch.parse('*.js');
console.log(picomatch.toRegex(output));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
<br>
## Options
### Picomatch options
The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` |
| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. |
| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
| `matchBase` | `boolean` | `false` | Alias for `basename` |
| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. |
| `noext` | `boolean` | `false` | Alias for `noextglob` |
| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. |
| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself |
| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. |
picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error.
### Scan Options
In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.scan('!./foo/*.js', { tokens: true });
console.log(result);
// {
// prefix: '!./',
// input: '!./foo/*.js',
// start: 3,
// base: 'foo',
// glob: '*.js',
// isBrace: false,
// isBracket: false,
// isGlob: true,
// isExtglob: false,
// isGlobstar: false,
// negated: true,
// maxDepth: 2,
// tokens: [
// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
// { value: 'foo', depth: 1, isGlob: false },
// { value: '*.js', depth: 1, isGlob: true }
// ],
// slashes: [ 2, 6 ],
// parts: [ 'foo', '*.js' ]
// }
```
<br>
### Options Examples
#### options.expandRange
**Type**: `function`
**Default**: `undefined`
Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
**Example**
The following example shows how to create a glob that matches a folder
```js
const fill = require('fill-range');
const regex = pm.makeRe('foo/{01..25}/bar', {
expandRange(a, b) {
return `(${fill(a, b, { toRegex: true })})`;
}
});
console.log(regex);
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false
```
#### options.format
**Type**: `function`
**Default**: `undefined`
Custom function for formatting strings before they're matched.
**Example**
```js
// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')); //=> true
```
#### options.onMatch
```js
const onMatch = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onMatch });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onIgnore
```js
const onIgnore = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onResult
```js
const onResult = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
<br>
<br>
## Globbing features
* [Basic globbing](#basic-globbing) (Wildcard matching)
* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
### Basic globbing
| **Character** | **Description** |
| --- | --- |
| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
#### Matching behavior vs. Bash
Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
<br>
### Advanced globbing
* [extglobs](#extglobs)
* [POSIX brackets](#posix-brackets)
* [Braces](#brace-expansion)
#### Extglobs
| **Pattern** | **Description** |
| --- | --- |
| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
| `!(pattern)` | Match _anything but_ `pattern` |
**Examples**
```js
const pm = require('picomatch');
// *(pattern) matches ZERO or more of "pattern"
console.log(pm.isMatch('a', 'a*(z)')); // true
console.log(pm.isMatch('az', 'a*(z)')); // true
console.log(pm.isMatch('azzz', 'a*(z)')); // true
// +(pattern) matches ONE or more of "pattern"
console.log(pm.isMatch('a', 'a*(z)')); // true
console.log(pm.isMatch('az', 'a*(z)')); // true
console.log(pm.isMatch('azzz', 'a*(z)')); // true
// supports multiple extglobs
console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
// supports nested extglobs
console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
```
#### POSIX brackets
POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
**Enable POSIX bracket support**
```js
console.log(pm.makeRe('[[:word:]]+', { posix: true }));
//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
```
**Supported POSIX classes**
The following named POSIX bracket expressions are supported:
* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
### Braces
Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces.
### Matching special characters as literals
If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
**Special Characters**
Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
To match any of the following characters as literals: `$^*+?()[]
Examples:
```js
console.log(pm.makeRe('foo/bar \\(1\\)'));
console.log(pm.makeRe('foo/bar \\(1\\)'));
```
<br>
<br>
## Library Comparisons
The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
| File system operations | - | - | - | - | - | - | - |
<br>
<br>
## Benchmarks
Performance comparison of picomatch and minimatch.
```
# .makeRe star
picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled)
minimatch x 627,206 ops/sec ±1.96% (87 runs sampled))
# .makeRe star; dot=true
picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled)
minimatch x 525,876 ops/sec ±0.60% (88 runs sampled)
# .makeRe globstar
picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled)
minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d)
# .makeRe globstars
picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled)
minimatch x 477,179 ops/sec ±1.33% (91 runs sampled)
# .makeRe with leading star
picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled)
minimatch x 453,564 ops/sec ±1.43% (94 runs sampled)
# .makeRe - basic braces
picomatch x 392,067 ops/sec ±0.70% (90 runs sampled)
minimatch x 99,532 ops/sec ±2.03% (87 runs sampled))
```
<br>
<br>
## Philosophies
The goal of this library is to be blazing fast, without compromising on accuracy.
**Accuracy**
The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
**Performance**
Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
<br>
<br>
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

View file

@ -0,0 +1,3 @@
'use strict';
module.exports = require('./lib/picomatch');

View file

@ -0,0 +1,179 @@
'use strict';
const path = require('path');
const WIN_SLASH = '\\\\/';
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
* Posix glob regex
*/
const DOT_LITERAL = '\\.';
const PLUS_LITERAL = '\\+';
const QMARK_LITERAL = '\\?';
const SLASH_LITERAL = '\\/';
const ONE_CHAR = '(?=.)';
const QMARK = '[^/]';
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const NO_DOT = `(?!${DOT_LITERAL})`;
const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
const STAR = `${QMARK}*?`;
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE = {
alnum: 'a-zA-Z0-9',
alpha: 'a-zA-Z',
ascii: '\\x00-\\x7F',
blank: ' \\t',
cntrl: '\\x00-\\x1F\\x7F',
digit: '0-9',
graph: '\\x21-\\x7E',
lower: 'a-z',
print: '\\x20-\\x7E ',
punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
space: ' \\t\\r\\n\\v\\f',
upper: 'A-Z',
word: 'A-Za-z0-9_',
xdigit: 'A-Fa-f0-9'
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
'***': '*',
'**/**': '**',
'**/**/**': '**'
},
// Digits
CHAR_0: 48, /* 0 */
CHAR_9: 57, /* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65, /* A */
CHAR_LOWERCASE_A: 97, /* a */
CHAR_UPPERCASE_Z: 90, /* Z */
CHAR_LOWERCASE_Z: 122, /* z */
CHAR_LEFT_PARENTHESES: 40, /* ( */
CHAR_RIGHT_PARENTHESES: 41, /* ) */
CHAR_ASTERISK: 42, /* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38, /* & */
CHAR_AT: 64, /* @ */
CHAR_BACKWARD_SLASH: 92, /* \ */
CHAR_CARRIAGE_RETURN: 13, /* \r */
CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
CHAR_COLON: 58, /* : */
CHAR_COMMA: 44, /* , */
CHAR_DOT: 46, /* . */
CHAR_DOUBLE_QUOTE: 34, /* " */
CHAR_EQUAL: 61, /* = */
CHAR_EXCLAMATION_MARK: 33, /* ! */
CHAR_FORM_FEED: 12, /* \f */
CHAR_FORWARD_SLASH: 47, /* / */
CHAR_GRAVE_ACCENT: 96, /* ` */
CHAR_HASH: 35, /* # */
CHAR_HYPHEN_MINUS: 45, /* - */
CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
CHAR_LEFT_CURLY_BRACE: 123, /* { */
CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
CHAR_LINE_FEED: 10, /* \n */
CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
CHAR_PERCENT: 37, /* % */
CHAR_PLUS: 43, /* + */
CHAR_QUESTION_MARK: 63, /* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
CHAR_RIGHT_CURLY_BRACE: 125, /* } */
CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
CHAR_SEMICOLON: 59, /* ; */
CHAR_SINGLE_QUOTE: 39, /* ' */
CHAR_SPACE: 32, /* */
CHAR_TAB: 9, /* \t */
CHAR_UNDERSCORE: 95, /* _ */
CHAR_VERTICAL_LINE: 124, /* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
SEP: path.sep,
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
'!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
'?': { type: 'qmark', open: '(?:', close: ')?' },
'+': { type: 'plus', open: '(?:', close: ')+' },
'*': { type: 'star', open: '(?:', close: ')*' },
'@': { type: 'at', open: '(?:', close: ')' }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,342 @@
'use strict';
const path = require('path');
const scan = require('./scan');
const parse = require('./parse');
const utils = require('./utils');
const constants = require('./constants');
const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
/**
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch(glob[, options]);
*
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
* @api public
*/
const picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map(input => picomatch(input, options, returnState));
const arrayMatcher = str => {
for (const isMatch of fns) {
const state = isMatch(str);
if (state) return state;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === '' || (typeof glob !== 'string' && !isState)) {
throw new TypeError('Expected pattern to be a non-empty string');
}
const opts = options || {};
const posix = utils.isWindows(options);
const regex = isState
? picomatch.compileRe(glob, options)
: picomatch.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
const result = { glob, state, regex, posix, input, output, match, isMatch };
if (typeof opts.onResult === 'function') {
opts.onResult(result);
}
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === 'function') {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === 'function') {
opts.onMatch(result);
}
return returnObject ? result : true;
};
if (returnState) {
matcher.state = state;
}
return matcher;
};
/**
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
* ```
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
* @api public
*/
picomatch.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string');
}
if (input === '') {
return { isMatch: false, output: '' };
}
const opts = options || {};
const format = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = (match && format) ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix);
} else {
match = regex.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(path.basename(input));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
picomatch.scan = (input, options) => scan(input, options);
/**
* Compile a regular expression from the `state` object returned by the
* [parse()](#parse) method.
*
* @param {Object} `state`
* @param {Object} `options`
* @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
* @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* @return {RegExp}
* @api public
*/
picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options || {};
const prepend = opts.contains ? '' : '^';
const append = opts.contains ? '' : '$';
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = state;
}
return regex;
};
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== 'string') {
throw new TypeError('Expected a non-empty string');
}
let parsed = { negated: false, fastpaths: true };
if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
parsed.output = parse.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse(input, options);
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
/**
* Picomatch constants.
* @return {Object}
*/
picomatch.constants = constants;
/**
* Expose "picomatch"
*/
module.exports = picomatch;

View file

@ -0,0 +1,391 @@
'use strict';
const utils = require('./utils');
const {
CHAR_ASTERISK, /* * */
CHAR_AT, /* @ */
CHAR_BACKWARD_SLASH, /* \ */
CHAR_COMMA, /* , */
CHAR_DOT, /* . */
CHAR_EXCLAMATION_MARK, /* ! */
CHAR_FORWARD_SLASH, /* / */
CHAR_LEFT_CURLY_BRACE, /* { */
CHAR_LEFT_PARENTHESES, /* ( */
CHAR_LEFT_SQUARE_BRACKET, /* [ */
CHAR_PLUS, /* + */
CHAR_QUESTION_MARK, /* ? */
CHAR_RIGHT_CURLY_BRACE, /* } */
CHAR_RIGHT_PARENTHESES, /* ) */
CHAR_RIGHT_SQUARE_BRACKET /* ] */
} = require('./constants');
const isPathSeparator = code => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = token => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = { value: '', depth: 0, isGlob: false };
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: '', depth: 0, isGlob: false };
if (finished === true) continue;
if (prev === CHAR_DOT && index === (start + 1)) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS
|| code === CHAR_AT
|| code === CHAR_ASTERISK
|| code === CHAR_QUESTION_MARK
|| code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = '';
let glob = '';
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = '';
glob = str;
} else {
base = str;
}
if (base && base !== '' && base !== '/' && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob) glob = utils.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== '') {
parts.push(value);
}
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan;

Some files were not shown because too many files have changed in this diff Show more