chore: Update deps

This commit is contained in:
BluJ
2023-02-27 10:38:56 -07:00
parent eec99c06bf
commit 60eb3a8e4b
736 changed files with 133547 additions and 2 deletions

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/tc39/proposal-accessible-object-hasownproperty/blob/main/polyfill.js
if (!Object.hasOwn) {
Object.defineProperty(Object, "hasOwn", {
value: function (object, property) {
if (object == null) {
throw new TypeError("Cannot convert undefined or null to object");
}
return Object.prototype.hasOwnProperty.call(Object(object), property);
},
configurable: true,
enumerable: false,
writable: true,
});
}

66
lib/script/_dnt.shims.js Normal file
View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dntGlobalThis = exports.Deno = void 0;
const shim_deno_1 = require("@deno/shim-deno");
var shim_deno_2 = require("@deno/shim-deno");
Object.defineProperty(exports, "Deno", { enumerable: true, get: function () { return shim_deno_2.Deno; } });
const dntGlobals = {
Deno: shim_deno_1.Deno,
};
exports.dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
// deno-lint-ignore ban-types
function createMergeProxy(baseObj, extObj) {
return new Proxy(baseObj, {
get(_target, prop, _receiver) {
if (prop in extObj) {
return extObj[prop];
}
else {
return baseObj[prop];
}
},
set(_target, prop, value) {
if (prop in extObj) {
delete extObj[prop];
}
baseObj[prop] = value;
return true;
},
deleteProperty(_target, prop) {
let success = false;
if (prop in extObj) {
delete extObj[prop];
success = true;
}
if (prop in baseObj) {
delete baseObj[prop];
success = true;
}
return success;
},
ownKeys(_target) {
const baseKeys = Reflect.ownKeys(baseObj);
const extKeys = Reflect.ownKeys(extObj);
const extKeysSet = new Set(extKeys);
return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
},
defineProperty(_target, prop, desc) {
if (prop in extObj) {
delete extObj[prop];
}
Reflect.defineProperty(baseObj, prop, desc);
return true;
},
getOwnPropertyDescriptor(_target, prop) {
if (prop in extObj) {
return Reflect.getOwnPropertyDescriptor(extObj, prop);
}
else {
return Reflect.getOwnPropertyDescriptor(baseObj, prop);
}
},
has(_target, prop) {
return prop in extObj || prop in baseObj;
},
});
}

View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dntGlobalThis = exports.Deno = void 0;
const shim_deno_1 = require("@deno/shim-deno");
var shim_deno_2 = require("@deno/shim-deno");
Object.defineProperty(exports, "Deno", { enumerable: true, get: function () { return shim_deno_2.Deno; } });
const dntGlobals = {
Deno: shim_deno_1.Deno,
};
exports.dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
// deno-lint-ignore ban-types
function createMergeProxy(baseObj, extObj) {
return new Proxy(baseObj, {
get(_target, prop, _receiver) {
if (prop in extObj) {
return extObj[prop];
}
else {
return baseObj[prop];
}
},
set(_target, prop, value) {
if (prop in extObj) {
delete extObj[prop];
}
baseObj[prop] = value;
return true;
},
deleteProperty(_target, prop) {
let success = false;
if (prop in extObj) {
delete extObj[prop];
success = true;
}
if (prop in baseObj) {
delete baseObj[prop];
success = true;
}
return success;
},
ownKeys(_target) {
const baseKeys = Reflect.ownKeys(baseObj);
const extKeys = Reflect.ownKeys(extObj);
const extKeysSet = new Set(extKeys);
return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
},
defineProperty(_target, prop, desc) {
if (prop in extObj) {
delete extObj[prop];
}
Reflect.defineProperty(baseObj, prop, desc);
return true;
},
getOwnPropertyDescriptor(_target, prop) {
if (prop in extObj) {
return Reflect.getOwnPropertyDescriptor(extObj, prop);
}
else {
return Reflect.getOwnPropertyDescriptor(baseObj, prop);
}
},
has(_target, prop) {
return prop in extObj || prop in baseObj;
},
});
}

133
lib/script/backups.js Normal file
View File

@@ -0,0 +1,133 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Backups = exports.DEFAULT_OPTIONS = void 0;
const util_js_1 = require("./util.js");
exports.DEFAULT_OPTIONS = {
delete: true,
force: true,
ignoreExisting: false,
exclude: [],
};
/**
* This utility simplifies the volume backup process.
* ```ts
* export const { createBackup, restoreBackup } = Backups.volumes("main").build();
* ```
*
* Changing the options of the rsync, (ie exludes) use either
* ```ts
* Backups.volumes("main").set_options({exclude: ['bigdata/']}).volumes('excludedVolume').build()
* // or
* Backups.with_options({exclude: ['bigdata/']}).volumes('excludedVolume').build()
* ```
*
* Using the more fine control, using the addSets for more control
* ```ts
* Backups.addSets({
* srcVolume: 'main', srcPath:'smallData/', dstPath: 'main/smallData/', dstVolume: : Backups.BACKUP
* }, {
* srcVolume: 'main', srcPath:'bigData/', dstPath: 'main/bigData/', dstVolume: : Backups.BACKUP, options: {exclude:['bigData/excludeThis']}}
* ).build()
* ```
*/
class Backups {
constructor(options = exports.DEFAULT_OPTIONS, backupSet = []) {
Object.defineProperty(this, "options", {
enumerable: true,
configurable: true,
writable: true,
value: options
});
Object.defineProperty(this, "backupSet", {
enumerable: true,
configurable: true,
writable: true,
value: backupSet
});
}
static volumes(...volumeNames) {
return new Backups().addSets(...volumeNames.map((srcVolume) => ({
srcVolume,
srcPath: "./",
dstPath: `./${srcVolume}/`,
dstVolume: Backups.BACKUP,
})));
}
static addSets(...options) {
return new Backups().addSets(...options);
}
static with_options(options) {
return new Backups({ ...exports.DEFAULT_OPTIONS, ...options });
}
set_options(options) {
this.options = {
...this.options,
...options,
};
return this;
}
volumes(...volumeNames) {
return this.addSets(...volumeNames.map((srcVolume) => ({
srcVolume,
srcPath: "./",
dstPath: `./${srcVolume}/`,
dstVolume: Backups.BACKUP,
})));
}
addSets(...options) {
options.forEach((x) => this.backupSet.push({ ...x, options: { ...this.options, ...x.options } }));
return this;
}
build() {
const createBackup = async (effects) => {
for (const item of this.backupSet) {
if (notEmptyPath(item.dstPath)) {
await effects.createDir({
volumeId: item.dstVolume,
path: item.dstPath,
});
}
await effects.runRsync({
...item,
options: {
...this.options,
...item.options,
},
}).wait();
}
return util_js_1.ok;
};
const restoreBackup = async (effects) => {
for (const item of this.backupSet) {
if (notEmptyPath(item.srcPath)) {
await effects.createDir({
volumeId: item.srcVolume,
path: item.srcPath,
});
}
await effects.runRsync({
options: {
...this.options,
...item.options,
},
srcVolume: item.dstVolume,
dstVolume: item.srcVolume,
srcPath: item.dstPath,
dstPath: item.srcPath,
}).wait();
}
return util_js_1.ok;
};
return { createBackup, restoreBackup };
}
}
exports.Backups = Backups;
Object.defineProperty(Backups, "BACKUP", {
enumerable: true,
configurable: true,
writable: true,
value: "BACKUP"
});
function notEmptyPath(file) {
return ["", ".", "./"].indexOf(file) === -1;
}

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConfigAndMatcher = exports.getConfig = void 0;
const dependencies_js_1 = require("../dependencies.js");
const dependencies_js_2 = require("../dependencies.js");
const propertiesMatcher_js_1 = require("../utils/propertiesMatcher.js");
const { any, string, dictionary } = dependencies_js_2.matches;
const matchConfig = dictionary([string, any]);
/**
* Call with the configuration to get a standard getConfig for the expected exports
* Assumption: start9/config.yaml is where the config will be stored
* Throws: Error if there is no file
* Throws: Error if the config.yaml isn't yaml nor config shape
* @param spec
* @returns
*/
const getConfig = (spec) => async (effects) => {
const config = await effects
.readFile({
path: "start9/config.yaml",
volumeId: "main",
})
.then((x) => dependencies_js_1.YAML.parse(x))
.then((x) => matchConfig.unsafeCast(x))
.catch((e) => {
effects.info(`Got error ${e} while trying to read the config`);
return undefined;
});
return {
result: {
config,
spec: spec.build(),
},
};
};
exports.getConfig = getConfig;
/**
* Call with the configuration to get a standard getConfig for the expected exports
* Assumption: start9/config.yaml is where the config will be stored
* Throws: Error if there is no file
* Throws: Error if the config.yaml isn't yaml nor config shape
* @param spec
* @returns A funnction for getConfig and the matcher for the spec sent in
*/
const getConfigAndMatcher = (spec) => {
const specBuilt = spec.build();
return [
async (effects) => {
const config = await effects
.readFile({
path: "start9/config.yaml",
volumeId: "main",
})
.then((x) => dependencies_js_1.YAML.parse(x))
.then((x) => matchConfig.unsafeCast(x))
.catch((e) => {
effects.info(`Got error ${e} while trying to read the config`);
return undefined;
});
return {
result: {
config,
spec: specBuilt,
},
};
},
(0, propertiesMatcher_js_1.typeFromProps)(specBuilt),
];
};
exports.getConfigAndMatcher = getConfigAndMatcher;

View File

@@ -0,0 +1,117 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromMapping = exports.initNoRepeat = exports.noRepeatGuard = exports.updateConfig = void 0;
const mod_js_1 = require("./mod.js");
const M = __importStar(require("../migrations.js"));
const util = __importStar(require("../util.js"));
const mod_js_2 = require("../emver-lite/mod.js");
const mod_js_3 = require("../config/mod.js");
/**
* @param fn function making desired modifications to the config
* @param configured whether or not the service should be considered "configured"
* @param noRepeat (optional) supply the version and type of the migration
* @param noFail (optional, default:false) whether or not to fail the migration if fn throws an error
* @returns a migraion function
*/
function updateConfig(fn, configured, noRepeat, noFail = false) {
return M.migrationFn(async (effects) => {
await noRepeatGuard(effects, noRepeat, async () => {
let config = util.unwrapResultType(await (0, mod_js_1.getConfig)(mod_js_3.Config.of({}))(effects)).config;
if (config) {
try {
config = await fn(config, effects);
}
catch (e) {
if (!noFail) {
throw e;
}
else {
configured = false;
}
}
util.unwrapResultType(await (0, mod_js_1.setConfig)(effects, config));
}
});
return { configured };
});
}
exports.updateConfig = updateConfig;
async function noRepeatGuard(effects, noRepeat, fn) {
if (!noRepeat) {
return fn();
}
if (!(await util.exists(effects, {
path: "start9/migrations",
volumeId: "main",
}))) {
await effects.createDir({ path: "start9/migrations", volumeId: "main" });
}
const migrationPath = {
path: `start9/migrations/${noRepeat.version}.complete`,
volumeId: "main",
};
if (noRepeat.type === "up") {
if (!(await util.exists(effects, migrationPath))) {
await fn();
await effects.writeFile({ ...migrationPath, toWrite: "" });
}
}
else if (noRepeat.type === "down") {
if (await util.exists(effects, migrationPath)) {
await fn();
await effects.removeFile(migrationPath);
}
}
}
exports.noRepeatGuard = noRepeatGuard;
async function initNoRepeat(effects, migrations, startingVersion) {
if (!(await util.exists(effects, {
path: "start9/migrations",
volumeId: "main",
}))) {
const starting = mod_js_2.EmVer.parse(startingVersion);
await effects.createDir({ path: "start9/migrations", volumeId: "main" });
for (const version in migrations) {
const migrationVersion = mod_js_2.EmVer.parse(version);
if (migrationVersion.lessThanOrEqual(starting)) {
await effects.writeFile({
path: `start9/migrations/${version}.complete`,
volumeId: "main",
toWrite: "",
});
}
}
}
}
exports.initNoRepeat = initNoRepeat;
function fromMapping(migrations, currentVersion) {
const inner = M.fromMapping(migrations, currentVersion);
return async (effects, version, direction) => {
await initNoRepeat(effects, migrations, direction === "from" ? version : currentVersion);
return inner(effects, version, direction);
};
}
exports.fromMapping = fromMapping;

34
lib/script/compat/mod.js Normal file
View File

@@ -0,0 +1,34 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.migrations = exports.getConfigAndMatcher = exports.getConfig = exports.setConfig = exports.properties = void 0;
var properties_js_1 = require("./properties.js");
Object.defineProperty(exports, "properties", { enumerable: true, get: function () { return properties_js_1.properties; } });
var setConfig_js_1 = require("./setConfig.js");
Object.defineProperty(exports, "setConfig", { enumerable: true, get: function () { return setConfig_js_1.setConfig; } });
var getConfig_js_1 = require("./getConfig.js");
Object.defineProperty(exports, "getConfig", { enumerable: true, get: function () { return getConfig_js_1.getConfig; } });
Object.defineProperty(exports, "getConfigAndMatcher", { enumerable: true, get: function () { return getConfig_js_1.getConfigAndMatcher; } });
exports.migrations = __importStar(require("./migrations.js"));

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.properties = void 0;
const dependencies_js_1 = require("../dependencies.js");
const util_js_1 = require("../util.js");
// deno-lint-ignore no-explicit-any
const asResult = (result) => ({ result: result });
const noPropertiesFound = {
result: {
version: 2,
data: {
"Not Ready": {
type: "string",
value: "Could not find properties. The service might still be starting",
qr: false,
copyable: false,
masked: false,
description: "Fallback Message When Properties could not be found",
},
},
},
};
/**
* Default will pull from a file (start9/stats.yaml) expected to be made on the main volume
* Assumption: start9/stats.yaml is created by some process
* Throws: stats.yaml isn't yaml
* @param effects
* @returns
*/
const properties = async (effects) => {
if (await (0, util_js_1.exists)(effects, { path: "start9/stats.yaml", volumeId: "main" }) ===
false) {
return noPropertiesFound;
}
return await effects.readFile({
path: "start9/stats.yaml",
volumeId: "main",
}).then(dependencies_js_1.YAML.parse).then(asResult);
};
exports.properties = properties;

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setConfig = void 0;
const dependencies_js_1 = require("../dependencies.js");
/**
* Will set the config to the default start9/config.yaml
* Assumption: start9/config.yaml is the location of the configuration
* @param effects
* @param newConfig Config to be written to start9/config.yaml
* @param depends_on This would be the depends on for condition depends_on
* @returns
*/
const setConfig = async (effects, newConfig, dependsOn = {}) => {
await effects.createDir({
path: "start9",
volumeId: "main",
});
await effects.writeFile({
path: "start9/config.yaml",
toWrite: dependencies_js_1.YAML.stringify(newConfig),
volumeId: "main",
});
const result = {
signal: "SIGTERM",
"depends-on": dependsOn,
};
return { result };
};
exports.setConfig = setConfig;
const _typeConversionCheck = exports.setConfig;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IBuilder = void 0;
class IBuilder {
constructor(a) {
Object.defineProperty(this, "a", {
enumerable: true,
configurable: true,
writable: true,
value: a
});
}
build() {
return this.a;
}
}
exports.IBuilder = IBuilder;

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = void 0;
const builder_js_1 = require("./builder.js");
class Config extends builder_js_1.IBuilder {
static empty() {
return new Config({});
}
static withValue(key, value) {
return Config.empty().withValue(key, value);
}
static addValue(key, value) {
return Config.empty().withValue(key, value);
}
static of(spec) {
// deno-lint-ignore no-explicit-any
const answer = {};
for (const key in spec) {
// deno-lint-ignore no-explicit-any
answer[key] = spec[key].build();
}
return new Config(answer);
}
withValue(key, value) {
return new Config({
...this.a,
[key]: value.build(),
});
}
addValue(key, value) {
return new Config({
...this.a,
[key]: value.build(),
});
}
}
exports.Config = Config;

View File

@@ -0,0 +1,64 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const dntShim = __importStar(require("../_dnt.test_shims.js"));
const config_js_1 = require("./config.js");
const value_js_1 = require("./value.js");
const mod_js_1 = require("../deps/deno.land/x/expect@v0.2.9/mod.js");
const { test } = dntShim.Deno;
test("String", () => {
const bitcoinPropertiesBuilt = config_js_1.Config.of({
"peer-tor-address": value_js_1.Value.string({
name: "Peer tor address",
default: "",
description: "The Tor address of the peer interface",
warning: null,
nullable: false,
masked: true,
placeholder: null,
pattern: null,
"pattern-description": null,
textarea: null,
}),
}).build();
(0, mod_js_1.expect)(JSON.stringify(bitcoinPropertiesBuilt)).toEqual(
/*json*/ `{
"peer-tor-address": {
"type": "string",
"name": "Peer tor address",
"default": "",
"description": "The Tor address of the peer interface",
"warning": null,
"nullable": false,
"masked": true,
"placeholder": null,
"pattern": null,
"pattern-description": null,
"textarea": null
}}`
.replaceAll("\n", " ")
.replaceAll(/\s{2,}/g, "")
.replaceAll(": ", ":"));
});

72
lib/script/config/list.js Normal file
View File

@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.List = void 0;
const builder_js_1 = require("./builder.js");
class List extends builder_js_1.IBuilder {
// // deno-lint-ignore ban-types
// static boolean<A extends Description & Default<boolean[]> & { range: string; spec: {}; default: boolean }>(a: A) {
// return new List({
// type: "list" as const,
// subtype: "boolean" as const,
// ...a,
// });
// }
static string(a) {
return new List({
type: "list",
subtype: "string",
...a,
});
}
static number(a) {
return new List({
type: "list",
subtype: "number",
...a,
});
}
static enum(a) {
return new List({
type: "list",
subtype: "enum",
...a,
});
}
static obj(a) {
const { spec: previousSpec, ...rest } = a;
const { spec: previousSpecSpec, ...restSpec } = previousSpec;
const specSpec = previousSpecSpec.build();
const spec = {
...restSpec,
spec: specSpec,
};
const value = {
spec,
...rest,
};
return new List({
type: "list",
subtype: "object",
...value,
});
}
static union(a) {
const { spec: previousSpec, ...rest } = a;
const { variants: previousVariants, ...restSpec } = previousSpec;
const variants = previousVariants.build();
const spec = {
...restSpec,
variants,
};
const value = {
spec,
...rest,
};
return new List({
type: "list",
subtype: "union",
...value,
});
}
}
exports.List = List;

11
lib/script/config/mod.js Normal file
View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variants = exports.Value = exports.List = exports.Config = void 0;
var config_js_1 = require("./config.js");
Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_js_1.Config; } });
var list_js_1 = require("./list.js");
Object.defineProperty(exports, "List", { enumerable: true, get: function () { return list_js_1.List; } });
var value_js_1 = require("./value.js");
Object.defineProperty(exports, "Value", { enumerable: true, get: function () { return value_js_1.Value; } });
var variants_js_1 = require("./variants.js");
Object.defineProperty(exports, "Variants", { enumerable: true, get: function () { return variants_js_1.Variants; } });

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Value = void 0;
const builder_js_1 = require("./builder.js");
class Value extends builder_js_1.IBuilder {
static boolean(a) {
return new Value({
type: "boolean",
...a,
});
}
static string(a) {
return new Value({
type: "string",
...a,
});
}
static number(a) {
return new Value({
type: "number",
...a,
});
}
static enum(a) {
return new Value({
type: "enum",
...a,
});
}
static object(a) {
const { spec: previousSpec, ...rest } = a;
const spec = previousSpec.build();
return new Value({
type: "object",
...rest,
spec,
});
}
static union(a) {
const { variants: previousVariants, ...rest } = a;
const variants = previousVariants.build();
return new Value({
type: "union",
...rest,
variants,
});
}
static list(a) {
return new Value(a.build());
}
}
exports.Value = Value;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variants = void 0;
const builder_js_1 = require("./builder.js");
class Variants extends builder_js_1.IBuilder {
static of(a) {
// deno-lint-ignore no-explicit-any
const variants = {};
for (const key in a) {
// deno-lint-ignore no-explicit-any
variants[key] = a[key].build();
}
return new Variants(variants);
}
static empty() {
return Variants.of({});
}
static withVariant(key, value) {
return Variants.empty().withVariant(key, value);
}
withVariant(key, value) {
return new Variants({
...this.a,
[key]: value.build(),
});
}
}
exports.Variants = Variants;

View File

@@ -0,0 +1,28 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.YAML = exports.matches = void 0;
exports.matches = __importStar(require("./deps/deno.land/x/ts_matches@v5.3.0/mod.js"));
exports.YAML = __importStar(require("./deps/deno.land/std@0.140.0/encoding/yaml.js"));

View File

@@ -0,0 +1,19 @@
"use strict";
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.assert = exports.DenoStdInternalError = void 0;
class DenoStdInternalError extends Error {
constructor(message) {
super(message);
this.name = "DenoStdInternalError";
}
}
exports.DenoStdInternalError = DenoStdInternalError;
/** Make an assertion, if not `true`, then throw. */
function assert(expr, msg = "") {
if (!expr) {
throw new DenoStdInternalError(msg);
}
}
exports.assert = assert;

View File

@@ -0,0 +1,166 @@
"use strict";
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesList = void 0;
/**
* An abstraction of multiple Uint8Arrays
*/
class BytesList {
constructor() {
Object.defineProperty(this, "len", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "chunks", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
}
/**
* Total size of bytes
*/
size() {
return this.len;
}
/**
* Push bytes with given offset infos
*/
add(value, start = 0, end = value.byteLength) {
if (value.byteLength === 0 || end - start === 0) {
return;
}
checkRange(start, end, value.byteLength);
this.chunks.push({
value,
end,
start,
offset: this.len,
});
this.len += end - start;
}
/**
* Drop head `n` bytes.
*/
shift(n) {
if (n === 0) {
return;
}
if (this.len <= n) {
this.chunks = [];
this.len = 0;
return;
}
const idx = this.getChunkIndex(n);
this.chunks.splice(0, idx);
const [chunk] = this.chunks;
if (chunk) {
const diff = n - chunk.offset;
chunk.start += diff;
}
let offset = 0;
for (const chunk of this.chunks) {
chunk.offset = offset;
offset += chunk.end - chunk.start;
}
this.len = offset;
}
/**
* Find chunk index in which `pos` locates by binary-search
* returns -1 if out of range
*/
getChunkIndex(pos) {
let max = this.chunks.length;
let min = 0;
while (true) {
const i = min + Math.floor((max - min) / 2);
if (i < 0 || this.chunks.length <= i) {
return -1;
}
const { offset, start, end } = this.chunks[i];
const len = end - start;
if (offset <= pos && pos < offset + len) {
return i;
}
else if (offset + len <= pos) {
min = i + 1;
}
else {
max = i - 1;
}
}
}
/**
* Get indexed byte from chunks
*/
get(i) {
if (i < 0 || this.len <= i) {
throw new Error("out of range");
}
const idx = this.getChunkIndex(i);
const { value, offset, start } = this.chunks[idx];
return value[start + i - offset];
}
/**
* Iterator of bytes from given position
*/
*iterator(start = 0) {
const startIdx = this.getChunkIndex(start);
if (startIdx < 0)
return;
const first = this.chunks[startIdx];
let firstOffset = start - first.offset;
for (let i = startIdx; i < this.chunks.length; i++) {
const chunk = this.chunks[i];
for (let j = chunk.start + firstOffset; j < chunk.end; j++) {
yield chunk.value[j];
}
firstOffset = 0;
}
}
/**
* Returns subset of bytes copied
*/
slice(start, end = this.len) {
if (end === start) {
return new Uint8Array();
}
checkRange(start, end, this.len);
const result = new Uint8Array(end - start);
const startIdx = this.getChunkIndex(start);
const endIdx = this.getChunkIndex(end - 1);
let written = 0;
for (let i = startIdx; i < endIdx; i++) {
const chunk = this.chunks[i];
const len = chunk.end - chunk.start;
result.set(chunk.value.subarray(chunk.start, chunk.end), written);
written += len;
}
const last = this.chunks[endIdx];
const rest = end - start - written;
result.set(last.value.subarray(last.start, last.start + rest), written);
return result;
}
/**
* Concatenate chunks into single Uint8Array copied.
*/
concat() {
const result = new Uint8Array(this.len);
let sum = 0;
for (const { value, start, end } of this.chunks) {
result.set(value.subarray(start, end), sum);
sum += end - start;
}
return result;
}
}
exports.BytesList = BytesList;
function checkRange(start, end, len) {
if (start < 0 || len < start || end < 0 || len < end || end < start) {
throw new Error("invalid range");
}
}

View File

@@ -0,0 +1,53 @@
"use strict";
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = exports.equalsSimd = exports.equalsNaive = void 0;
/** Check whether binary arrays are equal to each other using 8-bit comparisons.
* @private
* @param a first array to check equality
* @param b second array to check equality
*/
function equalsNaive(a, b) {
if (a.length !== b.length)
return false;
for (let i = 0; i < b.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
exports.equalsNaive = equalsNaive;
/** Check whether binary arrays are equal to each other using 32-bit comparisons.
* @private
* @param a first array to check equality
* @param b second array to check equality
*/
function equalsSimd(a, b) {
if (a.length !== b.length)
return false;
const len = a.length;
const compressable = Math.floor(len / 4);
const compressedA = new Uint32Array(a.buffer, 0, compressable);
const compressedB = new Uint32Array(b.buffer, 0, compressable);
for (let i = compressable * 4; i < len; i++) {
if (a[i] !== b[i])
return false;
}
for (let i = 0; i < compressedA.length; i++) {
if (compressedA[i] !== compressedB[i])
return false;
}
return true;
}
exports.equalsSimd = equalsSimd;
/** Check whether binary arrays are equal to each other.
* @param a first array to check equality
* @param b second array to check equality
*/
function equals(a, b) {
if (a.length < 1000)
return equalsNaive(a, b);
return equalsSimd(a, b);
}
exports.equals = equals;

View File

@@ -0,0 +1,253 @@
"use strict";
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = exports.copy = exports.includesNeedle = exports.concat = exports.repeat = exports.endsWith = exports.startsWith = exports.lastIndexOfNeedle = exports.indexOfNeedle = void 0;
/**
* Provides helper functions to manipulate `Uint8Array` byte slices that are not
* included on the `Uint8Array` prototype.
*
* @module
*/
/** Returns the index of the first occurrence of the needle array in the source
* array, or -1 if it is not present.
*
* A start index can be specified as the third argument that begins the search
* at that given index. The start index defaults to the start of the array.
*
* The complexity of this function is O(source.lenth * needle.length).
*
* ```ts
* import { indexOfNeedle } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
* const needle = new Uint8Array([1, 2]);
* console.log(indexOfNeedle(source, needle)); // 1
* console.log(indexOfNeedle(source, needle, 2)); // 3
* ```
*/
function indexOfNeedle(source, needle, start = 0) {
if (start >= source.length) {
return -1;
}
if (start < 0) {
start = Math.max(0, source.length + start);
}
const s = needle[0];
for (let i = start; i < source.length; i++) {
if (source[i] !== s)
continue;
const pin = i;
let matched = 1;
let j = i;
while (matched < needle.length) {
j++;
if (source[j] !== needle[j - pin]) {
break;
}
matched++;
}
if (matched === needle.length) {
return pin;
}
}
return -1;
}
exports.indexOfNeedle = indexOfNeedle;
/** Returns the index of the last occurrence of the needle array in the source
* array, or -1 if it is not present.
*
* A start index can be specified as the third argument that begins the search
* at that given index. The start index defaults to the end of the array.
*
* The complexity of this function is O(source.lenth * needle.length).
*
* ```ts
* import { lastIndexOfNeedle } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
* const needle = new Uint8Array([1, 2]);
* console.log(lastIndexOfNeedle(source, needle)); // 5
* console.log(lastIndexOfNeedle(source, needle, 4)); // 3
* ```
*/
function lastIndexOfNeedle(source, needle, start = source.length - 1) {
if (start < 0) {
return -1;
}
if (start >= source.length) {
start = source.length - 1;
}
const e = needle[needle.length - 1];
for (let i = start; i >= 0; i--) {
if (source[i] !== e)
continue;
const pin = i;
let matched = 1;
let j = i;
while (matched < needle.length) {
j--;
if (source[j] !== needle[needle.length - 1 - (pin - j)]) {
break;
}
matched++;
}
if (matched === needle.length) {
return pin - needle.length + 1;
}
}
return -1;
}
exports.lastIndexOfNeedle = lastIndexOfNeedle;
/** Returns true if the prefix array appears at the start of the source array,
* false otherwise.
*
* The complexity of this function is O(prefix.length).
*
* ```ts
* import { startsWith } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
* const prefix = new Uint8Array([0, 1, 2]);
* console.log(startsWith(source, prefix)); // true
* ```
*/
function startsWith(source, prefix) {
for (let i = 0, max = prefix.length; i < max; i++) {
if (source[i] !== prefix[i])
return false;
}
return true;
}
exports.startsWith = startsWith;
/** Returns true if the suffix array appears at the end of the source array,
* false otherwise.
*
* The complexity of this function is O(suffix.length).
*
* ```ts
* import { endsWith } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
* const suffix = new Uint8Array([1, 2, 3]);
* console.log(endsWith(source, suffix)); // true
* ```
*/
function endsWith(source, suffix) {
for (let srci = source.length - 1, sfxi = suffix.length - 1; sfxi >= 0; srci--, sfxi--) {
if (source[srci] !== suffix[sfxi])
return false;
}
return true;
}
exports.endsWith = endsWith;
/** Returns a new Uint8Array composed of `count` repetitions of the `source`
* array.
*
* If `count` is negative, a `RangeError` is thrown.
*
* ```ts
* import { repeat } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2]);
* console.log(repeat(source, 3)); // [0, 1, 2, 0, 1, 2, 0, 1, 2]
* console.log(repeat(source, 0)); // []
* console.log(repeat(source, -1)); // RangeError
* ```
*/
function repeat(source, count) {
if (count === 0) {
return new Uint8Array();
}
if (count < 0) {
throw new RangeError("bytes: negative repeat count");
}
else if ((source.length * count) / count !== source.length) {
throw new Error("bytes: repeat count causes overflow");
}
const int = Math.floor(count);
if (int !== count) {
throw new Error("bytes: repeat count must be an integer");
}
const nb = new Uint8Array(source.length * count);
let bp = copy(source, nb);
for (; bp < nb.length; bp *= 2) {
copy(nb.slice(0, bp), nb, bp);
}
return nb;
}
exports.repeat = repeat;
/** Concatenate the given arrays into a new Uint8Array.
*
* ```ts
* import { concat } from "./mod.ts";
* const a = new Uint8Array([0, 1, 2]);
* const b = new Uint8Array([3, 4, 5]);
* console.log(concat(a, b)); // [0, 1, 2, 3, 4, 5]
*/
function concat(...buf) {
let length = 0;
for (const b of buf) {
length += b.length;
}
const output = new Uint8Array(length);
let index = 0;
for (const b of buf) {
output.set(b, index);
index += b.length;
}
return output;
}
exports.concat = concat;
/** Returns true if the source array contains the needle array, false otherwise.
*
* A start index can be specified as the third argument that begins the search
* at that given index. The start index defaults to the beginning of the array.
*
* The complexity of this function is O(source.length * needle.length).
*
* ```ts
* import { includesNeedle } from "./mod.ts";
* const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
* const needle = new Uint8Array([1, 2]);
* console.log(includesNeedle(source, needle)); // true
* console.log(includesNeedle(source, needle, 6)); // false
* ```
*/
function includesNeedle(source, needle, start = 0) {
return indexOfNeedle(source, needle, start) !== -1;
}
exports.includesNeedle = includesNeedle;
/** Copy bytes from the `src` array to the `dst` array. Returns the number of
* bytes copied.
*
* If the `src` array is larger than what the `dst` array can hold, only the
* amount of bytes that fit in the `dst` array are copied.
*
* An offset can be specified as the third argument that begins the copy at
* that given index in the `dst` array. The offset defaults to the beginning of
* the array.
*
* ```ts
* import { copy } from "./mod.ts";
* const src = new Uint8Array([9, 8, 7]);
* const dst = new Uint8Array([0, 1, 2, 3, 4, 5]);
* console.log(copy(src, dst)); // 3
* console.log(dst); // [9, 8, 7, 3, 4, 5]
* ```
*
* ```ts
* import { copy } from "./mod.ts";
* const src = new Uint8Array([1, 1, 1, 1]);
* const dst = new Uint8Array([0, 0, 0, 0]);
* console.log(copy(src, dst, 1)); // 3
* console.log(dst); // [0, 1, 1, 1]
* ```
*/
function copy(src, dst, off = 0) {
off = Math.max(0, Math.min(off, dst.byteLength));
const dstBytesAvailable = dst.byteLength - off;
if (src.byteLength > dstBytesAvailable) {
src = src.subarray(0, dstBytesAvailable);
}
dst.set(src, off);
return src.byteLength;
}
exports.copy = copy;
var equals_js_1 = require("./equals.js");
Object.defineProperty(exports, "equals", { enumerable: true, get: function () { return equals_js_1.equals; } });

View File

@@ -0,0 +1,711 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.dump = void 0;
const error_js_1 = require("../error.js");
const common = __importStar(require("../utils.js"));
const dumper_state_js_1 = require("./dumper_state.js");
const _toString = Object.prototype.toString;
const { hasOwn } = Object;
const CHAR_TAB = 0x09; /* Tab */
const CHAR_LINE_FEED = 0x0a; /* LF */
const CHAR_SPACE = 0x20; /* Space */
const CHAR_EXCLAMATION = 0x21; /* ! */
const CHAR_DOUBLE_QUOTE = 0x22; /* " */
const CHAR_SHARP = 0x23; /* # */
const CHAR_PERCENT = 0x25; /* % */
const CHAR_AMPERSAND = 0x26; /* & */
const CHAR_SINGLE_QUOTE = 0x27; /* ' */
const CHAR_ASTERISK = 0x2a; /* * */
const CHAR_COMMA = 0x2c; /* , */
const CHAR_MINUS = 0x2d; /* - */
const CHAR_COLON = 0x3a; /* : */
const CHAR_GREATER_THAN = 0x3e; /* > */
const CHAR_QUESTION = 0x3f; /* ? */
const CHAR_COMMERCIAL_AT = 0x40; /* @ */
const CHAR_LEFT_SQUARE_BRACKET = 0x5b; /* [ */
const CHAR_RIGHT_SQUARE_BRACKET = 0x5d; /* ] */
const CHAR_GRAVE_ACCENT = 0x60; /* ` */
const CHAR_LEFT_CURLY_BRACKET = 0x7b; /* { */
const CHAR_VERTICAL_LINE = 0x7c; /* | */
const CHAR_RIGHT_CURLY_BRACKET = 0x7d; /* } */
const ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = "\\0";
ESCAPE_SEQUENCES[0x07] = "\\a";
ESCAPE_SEQUENCES[0x08] = "\\b";
ESCAPE_SEQUENCES[0x09] = "\\t";
ESCAPE_SEQUENCES[0x0a] = "\\n";
ESCAPE_SEQUENCES[0x0b] = "\\v";
ESCAPE_SEQUENCES[0x0c] = "\\f";
ESCAPE_SEQUENCES[0x0d] = "\\r";
ESCAPE_SEQUENCES[0x1b] = "\\e";
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5c] = "\\\\";
ESCAPE_SEQUENCES[0x85] = "\\N";
ESCAPE_SEQUENCES[0xa0] = "\\_";
ESCAPE_SEQUENCES[0x2028] = "\\L";
ESCAPE_SEQUENCES[0x2029] = "\\P";
const DEPRECATED_BOOLEANS_SYNTAX = [
"y",
"Y",
"yes",
"Yes",
"YES",
"on",
"On",
"ON",
"n",
"N",
"no",
"No",
"NO",
"off",
"Off",
"OFF",
];
function encodeHex(character) {
const string = character.toString(16).toUpperCase();
let handle;
let length;
if (character <= 0xff) {
handle = "x";
length = 2;
}
else if (character <= 0xffff) {
handle = "u";
length = 4;
}
else if (character <= 0xffffffff) {
handle = "U";
length = 8;
}
else {
throw new error_js_1.YAMLError("code point within a string may not be greater than 0xFFFFFFFF");
}
return `\\${handle}${common.repeat("0", length - string.length)}${string}`;
}
// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
const ind = common.repeat(" ", spaces), length = string.length;
let position = 0, next = -1, result = "", line;
while (position < length) {
next = string.indexOf("\n", position);
if (next === -1) {
line = string.slice(position);
position = length;
}
else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== "\n")
result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return `\n${common.repeat(" ", state.indent * level)}`;
}
function testImplicitResolving(state, str) {
let type;
for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isnt mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
return ((0x00020 <= c && c <= 0x00007e) ||
(0x000a1 <= c && c <= 0x00d7ff && c !== 0x2028 && c !== 0x2029) ||
(0x0e000 <= c && c <= 0x00fffd && c !== 0xfeff) /* BOM */ ||
(0x10000 <= c && c <= 0x10ffff));
}
// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c) {
// Uses a subset of nb-char - c-flow-indicator - ":" - "#"
// where nb-char ::= c-printable - b-char - c-byte-order-mark.
return (isPrintable(c) &&
c !== 0xfeff &&
// - c-flow-indicator
c !== CHAR_COMMA &&
c !== CHAR_LEFT_SQUARE_BRACKET &&
c !== CHAR_RIGHT_SQUARE_BRACKET &&
c !== CHAR_LEFT_CURLY_BRACKET &&
c !== CHAR_RIGHT_CURLY_BRACKET &&
// - ":" - "#"
c !== CHAR_COLON &&
c !== CHAR_SHARP);
}
// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
// Uses a subset of ns-char - c-indicator
// where ns-char = nb-char - s-white.
return (isPrintable(c) &&
c !== 0xfeff &&
!isWhitespace(c) && // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
c !== CHAR_MINUS &&
c !== CHAR_QUESTION &&
c !== CHAR_COLON &&
c !== CHAR_COMMA &&
c !== CHAR_LEFT_SQUARE_BRACKET &&
c !== CHAR_RIGHT_SQUARE_BRACKET &&
c !== CHAR_LEFT_CURLY_BRACKET &&
c !== CHAR_RIGHT_CURLY_BRACKET &&
// | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
c !== CHAR_SHARP &&
c !== CHAR_AMPERSAND &&
c !== CHAR_ASTERISK &&
c !== CHAR_EXCLAMATION &&
c !== CHAR_VERTICAL_LINE &&
c !== CHAR_GREATER_THAN &&
c !== CHAR_SINGLE_QUOTE &&
c !== CHAR_DOUBLE_QUOTE &&
// | “%” | “@” | “`”)
c !== CHAR_PERCENT &&
c !== CHAR_COMMERCIAL_AT &&
c !== CHAR_GRAVE_ACCENT);
}
// Determines whether block indentation indicator is required.
function needIndentIndicator(string) {
const leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string);
}
const STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5;
// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
const shouldTrackWidth = lineWidth !== -1;
let hasLineBreak = false, hasFoldableLine = false, // only checked if shouldTrackWidth
previousLineBreak = -1, // count the first line correctly
plain = isPlainSafeFirst(string.charCodeAt(0)) &&
!isWhitespace(string.charCodeAt(string.length - 1));
let char, i;
if (singleLineOnly) {
// Case: no block styles.
// Check for disallowed characters to rule out plain and single.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
}
else {
// Case: block styles permitted.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
// Check if any line can be folded.
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine ||
// Foldable line = too long, and not more-indented.
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== " ");
previousLineBreak = i;
}
}
else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
// in case the end is missing a \n
hasFoldableLine = hasFoldableLine ||
(shouldTrackWidth &&
i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== " ");
}
// Although every style can represent \n without escaping, prefer block styles
// for multiline, since they're more readable and they don't add empty lines.
// Also prefer folding a super-long line.
if (!hasLineBreak && !hasFoldableLine) {
// Strings interpretable as another type have to be quoted;
// e.g. the string 'true' vs. the boolean true.
return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (indentPerLevel > 9 && needIndentIndicator(string)) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
// Prefer literal style unless we want to fold.
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
if (line === "" || line[0] === " ")
return line;
// Since a more-indented line adds a \n, breaks can't be followed by a space.
const breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
let match;
// start is an inclusive index. end, curr, and next are exclusive.
let start = 0, end, curr = 0, next = 0;
let result = "";
// Invariants: 0 <= start <= length-1.
// 0 <= curr <= next <= max(0, length-2). curr - start <= width.
// Inside the loop:
// A match implies length >= 2, so curr and next are <= length-2.
// tslint:disable-next-line:no-conditional-assignment
while ((match = breakRe.exec(line))) {
next = match.index;
// maintain invariant: curr - start <= width
if (next - start > width) {
end = curr > start ? curr : next; // derive end <= length-2
result += `\n${line.slice(start, end)}`;
// skip the space that was output as \n
start = end + 1; // derive start <= length-1
}
curr = next;
}
// By the invariants, start <= length-1, so there is something left over.
// It is either the whole string or a part starting from non-whitespace.
result += "\n";
// Insert a break if the remainder is too long and there is a break available.
if (line.length - start > width && curr > start) {
result += `${line.slice(start, curr)}\n${line.slice(curr + 1)}`;
}
else {
result += line.slice(start);
}
return result.slice(1); // drop extra \n joiner
}
// (See the note for writeScalar.)
function dropEndingNewline(string) {
return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
}
// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
// In folded style, $k$ consecutive newlines output as $k+1$ newlines—
// unless they're before or after a more-indented line, or at the very
// beginning or end, in which case $k$ maps to $k$.
// Therefore, parse each chunk as newline(s) followed by a content line.
const lineRe = /(\n+)([^\n]*)/g;
// first line (possibly an empty line)
let result = (() => {
let nextLF = string.indexOf("\n");
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
})();
// If we haven't reached the first content line yet, don't add an extra \n.
let prevMoreIndented = string[0] === "\n" || string[0] === " ";
let moreIndented;
// rest of the lines
let match;
// tslint:disable-next-line:no-conditional-assignment
while ((match = lineRe.exec(string))) {
const prefix = match[1], line = match[2];
moreIndented = line[0] === " ";
result += prefix +
(!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") +
foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
// Escapes a double-quoted string.
function escapeString(string) {
let result = "";
let char, nextChar;
let escapeSeq;
for (let i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
// Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
if (char >= 0xd800 && char <= 0xdbff /* high surrogate */) {
nextChar = string.charCodeAt(i + 1);
if (nextChar >= 0xdc00 && nextChar <= 0xdfff /* low surrogate */) {
// Combine the surrogate pair and store it escaped.
result += encodeHex((char - 0xd800) * 0x400 + nextChar - 0xdc00 + 0x10000);
// Advance index one extra since we already used that char here.
i++;
continue;
}
}
escapeSeq = ESCAPE_SEQUENCES[char];
result += !escapeSeq && isPrintable(char)
? string[i]
: escapeSeq || encodeHex(char);
}
return result;
}
// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
const indentIndicator = needIndentIndicator(string)
? String(indentPerLevel)
: "";
// note the special case: the string '\n' counts as a "trailing" empty line.
const clip = string[string.length - 1] === "\n";
const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
const chomp = keep ? "+" : clip ? "" : "-";
return `${indentIndicator}${chomp}\n`;
}
// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
// since the dumper adds its own newline. This always works:
// • No ending newline => unaffected; already using strip "-" chomping.
// • Ending newline => removed then restored.
// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey) {
state.dump = (() => {
if (string.length === 0) {
return "''";
}
if (!state.noCompatMode &&
DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
return `'${string}'`;
}
const indent = state.indent * Math.max(1, level); // no 0-indent scalars
// As indentation gets deeper, let the width decrease monotonically
// to the lower bound min(state.lineWidth, 40).
// Note that this implies
// state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
// state.lineWidth > 40 + state.indent: width decreases until the lower
// bound.
// This behaves better than a constant minimum width which disallows
// narrower options, or an indent threshold which causes the width
// to suddenly increase.
const lineWidth = state.lineWidth === -1
? -1
: Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
// Without knowing if keys are implicit/explicit,
// assume implicit for safety.
const singleLineOnly = iskey ||
// No block styles in flow mode.
(state.flowLevel > -1 && level >= state.flowLevel);
function testAmbiguity(str) {
return testImplicitResolving(state, str);
}
switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return `'${string.replace(/'/g, "''")}'`;
case STYLE_LITERAL:
return `|${blockHeader(string, state.indent)}${dropEndingNewline(indentString(string, indent))}`;
case STYLE_FOLDED:
return `>${blockHeader(string, state.indent)}${dropEndingNewline(indentString(foldString(string, lineWidth), indent))}`;
case STYLE_DOUBLE:
return `"${escapeString(string)}"`;
default:
throw new error_js_1.YAMLError("impossible error: invalid scalar style");
}
})();
}
function writeFlowSequence(state, level, object) {
let _result = "";
const _tag = state.tag;
for (let index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level, object[index], false, false)) {
if (index !== 0)
_result += `,${!state.condenseFlow ? " " : ""}`;
_result += state.dump;
}
}
state.tag = _tag;
state.dump = `[${_result}]`;
}
function writeBlockSequence(state, level, object, compact = false) {
let _result = "";
const _tag = state.tag;
for (let index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level + 1, object[index], true, true)) {
if (!compact || index !== 0) {
_result += generateNextLine(state, level);
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += "-";
}
else {
_result += "- ";
}
_result += state.dump;
}
}
state.tag = _tag;
state.dump = _result || "[]"; // Empty sequence if no valid values.
}
function writeFlowMapping(state, level, object) {
let _result = "";
const _tag = state.tag, objectKeyList = Object.keys(object);
let pairBuffer, objectKey, objectValue;
for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = state.condenseFlow ? '"' : "";
if (index !== 0)
pairBuffer += ", ";
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level, objectKey, false, false)) {
continue; // Skip this pair because of invalid key;
}
if (state.dump.length > 1024)
pairBuffer += "? ";
pairBuffer += `${state.dump}${state.condenseFlow ? '"' : ""}:${state.condenseFlow ? "" : " "}`;
if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value.
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = `{${_result}}`;
}
function writeBlockMapping(state, level, object, compact = false) {
const _tag = state.tag, objectKeyList = Object.keys(object);
let _result = "";
// Allow sorting keys so that the output file is deterministic
if (state.sortKeys === true) {
// Default sorting
objectKeyList.sort();
}
else if (typeof state.sortKeys === "function") {
// Custom sort function
objectKeyList.sort(state.sortKeys);
}
else if (state.sortKeys) {
// Something is wrong
throw new error_js_1.YAMLError("sortKeys must be a boolean or a function");
}
let pairBuffer = "", objectKey, objectValue, explicitPair;
for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = "";
if (!compact || index !== 0) {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key.
}
explicitPair = (state.tag !== null && state.tag !== "?") ||
(state.dump && state.dump.length > 1024);
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += "?";
}
else {
pairBuffer += "? ";
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue; // Skip this pair because of invalid value.
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ":";
}
else {
pairBuffer += ": ";
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || "{}"; // Empty mapping if no valid pairs.
}
function detectType(state, object, explicit = false) {
const typeList = explicit ? state.explicitTypes : state.implicitTypes;
let type;
let style;
let _result;
for (let index = 0, length = typeList.length; index < length; index += 1) {
type = typeList[index];
if ((type.instanceOf || type.predicate) &&
(!type.instanceOf ||
(typeof object === "object" && object instanceof type.instanceOf)) &&
(!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : "?";
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === "[object Function]") {
_result = type.represent(object, style);
}
else if (hasOwn(type.represent, style)) {
_result = type.represent[style](object, style);
}
else {
throw new error_js_1.YAMLError(`!<${type.tag}> tag resolver accepts not "${style}" style`);
}
state.dump = _result;
}
return true;
}
}
return false;
}
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey = false) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
const type = _toString.call(state.dump);
if (block) {
block = state.flowLevel < 0 || state.flowLevel > level;
}
const objectOrArray = type === "[object Object]" || type === "[object Array]";
let duplicateIndex = -1;
let duplicate = false;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if ((state.tag !== null && state.tag !== "?") ||
duplicate ||
(state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = `*ref_${duplicateIndex}`;
}
else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === "[object Object]") {
if (block && Object.keys(state.dump).length !== 0) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = `&ref_${duplicateIndex}${state.dump}`;
}
}
else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = `&ref_${duplicateIndex} ${state.dump}`;
}
}
}
else if (type === "[object Array]") {
const arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
if (block && state.dump.length !== 0) {
writeBlockSequence(state, arrayLevel, state.dump, compact);
if (duplicate) {
state.dump = `&ref_${duplicateIndex}${state.dump}`;
}
}
else {
writeFlowSequence(state, arrayLevel, state.dump);
if (duplicate) {
state.dump = `&ref_${duplicateIndex} ${state.dump}`;
}
}
}
else if (type === "[object String]") {
if (state.tag !== "?") {
writeScalar(state, state.dump, level, iskey);
}
}
else {
if (state.skipInvalid)
return false;
throw new error_js_1.YAMLError(`unacceptable kind of an object to dump ${type}`);
}
if (state.tag !== null && state.tag !== "?") {
state.dump = `!<${state.tag}> ${state.dump}`;
}
}
return true;
}
function inspectNode(object, objects, duplicatesIndexes) {
if (object !== null && typeof object === "object") {
const index = objects.indexOf(object);
if (index !== -1) {
if (duplicatesIndexes.indexOf(index) === -1) {
duplicatesIndexes.push(index);
}
}
else {
objects.push(object);
if (Array.isArray(object)) {
for (let idx = 0, length = object.length; idx < length; idx += 1) {
inspectNode(object[idx], objects, duplicatesIndexes);
}
}
else {
const objectKeyList = Object.keys(object);
for (let idx = 0, length = objectKeyList.length; idx < length; idx += 1) {
inspectNode(object[objectKeyList[idx]], objects, duplicatesIndexes);
}
}
}
}
}
function getDuplicateReferences(object, state) {
const objects = [], duplicatesIndexes = [];
inspectNode(object, objects, duplicatesIndexes);
const length = duplicatesIndexes.length;
for (let index = 0; index < length; index += 1) {
state.duplicates.push(objects[duplicatesIndexes[index]]);
}
state.usedDuplicates = Array.from({ length });
}
function dump(input, options) {
options = options || {};
const state = new dumper_state_js_1.DumperState(options);
if (!state.noRefs)
getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true))
return `${state.dump}\n`;
return "";
}
exports.dump = dump;

View File

@@ -0,0 +1,152 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DumperState = void 0;
const state_js_1 = require("../state.js");
const { hasOwn } = Object;
function compileStyleMap(schema, map) {
if (typeof map === "undefined" || map === null)
return {};
let type;
const result = {};
const keys = Object.keys(map);
let tag, style;
for (let index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === "!!") {
tag = `tag:yaml.org,2002:${tag.slice(2)}`;
}
type = schema.compiledTypeMap.fallback[tag];
if (type &&
typeof type.styleAliases !== "undefined" &&
hasOwn(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
class DumperState extends state_js_1.State {
constructor({ schema, indent = 2, noArrayIndent = false, skipInvalid = false, flowLevel = -1, styles = null, sortKeys = false, lineWidth = 80, noRefs = false, noCompatMode = false, condenseFlow = false, }) {
super(schema);
Object.defineProperty(this, "indent", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "noArrayIndent", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "skipInvalid", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "flowLevel", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "sortKeys", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "lineWidth", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "noRefs", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "noCompatMode", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "condenseFlow", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "implicitTypes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "explicitTypes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "tag", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "result", {
enumerable: true,
configurable: true,
writable: true,
value: ""
});
Object.defineProperty(this, "duplicates", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "usedDuplicates", {
enumerable: true,
configurable: true,
writable: true,
value: []
}); // changed from null to []
Object.defineProperty(this, "styleMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "dump", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.indent = Math.max(1, indent);
this.noArrayIndent = noArrayIndent;
this.skipInvalid = skipInvalid;
this.flowLevel = flowLevel;
this.styleMap = compileStyleMap(this.schema, styles);
this.sortKeys = sortKeys;
this.lineWidth = lineWidth;
this.noRefs = noRefs;
this.noCompatMode = noCompatMode;
this.condenseFlow = condenseFlow;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
}
}
exports.DumperState = DumperState;

View File

@@ -0,0 +1,23 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.YAMLError = void 0;
class YAMLError extends Error {
constructor(message = "(unknown reason)", mark = "") {
super(`${message} ${mark}`);
Object.defineProperty(this, "mark", {
enumerable: true,
configurable: true,
writable: true,
value: mark
});
this.name = this.constructor.name;
}
toString(_compact) {
return `${this.name}: ${this.message} ${this.mark}`;
}
}
exports.YAMLError = YAMLError;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,154 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoaderState = void 0;
const state_js_1 = require("../state.js");
class LoaderState extends state_js_1.State {
constructor(input, { filename, schema, onWarning, legacy = false, json = false, listener = null, }) {
super(schema);
Object.defineProperty(this, "input", {
enumerable: true,
configurable: true,
writable: true,
value: input
});
Object.defineProperty(this, "documents", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "length", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "lineIndent", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "lineStart", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "position", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "line", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "filename", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "onWarning", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "legacy", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "json", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "listener", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "implicitTypes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "typeMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "version", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "checkLineBreaks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "tagMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "anchorMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "tag", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "anchor", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "kind", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "result", {
enumerable: true,
configurable: true,
writable: true,
value: ""
});
this.filename = filename;
this.onWarning = onWarning;
this.legacy = legacy;
this.json = json;
this.listener = listener;
this.implicitTypes = this.schema.compiledImplicit;
this.typeMap = this.schema.compiledTypeMap;
this.length = input.length;
}
}
exports.LoaderState = LoaderState;

View File

@@ -0,0 +1,85 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mark = void 0;
const utils_js_1 = require("./utils.js");
class Mark {
constructor(name, buffer, position, line, column) {
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: name
});
Object.defineProperty(this, "buffer", {
enumerable: true,
configurable: true,
writable: true,
value: buffer
});
Object.defineProperty(this, "position", {
enumerable: true,
configurable: true,
writable: true,
value: position
});
Object.defineProperty(this, "line", {
enumerable: true,
configurable: true,
writable: true,
value: line
});
Object.defineProperty(this, "column", {
enumerable: true,
configurable: true,
writable: true,
value: column
});
}
getSnippet(indent = 4, maxLength = 75) {
if (!this.buffer)
return null;
let head = "";
let start = this.position;
while (start > 0 &&
"\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1;
if (this.position - start > maxLength / 2 - 1) {
head = " ... ";
start += 5;
break;
}
}
let tail = "";
let end = this.position;
while (end < this.buffer.length &&
"\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1) {
end += 1;
if (end - this.position > maxLength / 2 - 1) {
tail = " ... ";
end -= 5;
break;
}
}
const snippet = this.buffer.slice(start, end);
return `${(0, utils_js_1.repeat)(" ", indent)}${head}${snippet}${tail}\n${(0, utils_js_1.repeat)(" ", indent + this.position - start + head.length)}^`;
}
toString(compact) {
let snippet, where = "";
if (this.name) {
where += `in "${this.name}" `;
}
where += `at line ${this.line + 1}, column ${this.column + 1}`;
if (!compact) {
snippet = this.getSnippet();
if (snippet) {
where += `:\n${snippet}`;
}
}
return where;
}
}
exports.Mark = Mark;

View File

@@ -0,0 +1,22 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseAll = exports.parse = void 0;
const loader_js_1 = require("./loader/loader.js");
/**
* Parses `content` as single YAML document.
*
* Returns a JavaScript object or throws `YAMLException` on error.
* By default, does not support regexps, functions and undefined. This method is safe for untrusted data.
*/
function parse(content, options) {
return (0, loader_js_1.load)(content, options);
}
exports.parse = parse;
function parseAll(content, iterator, options) {
return (0, loader_js_1.loadAll)(content, iterator, options);
}
exports.parseAll = parseAll;

View File

@@ -0,0 +1,106 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Schema = void 0;
const error_js_1 = require("./error.js");
function compileList(schema, name, result) {
const exclude = [];
for (const includedSchema of schema.include) {
result = compileList(includedSchema, name, result);
}
for (const currentType of schema[name]) {
for (let previousIndex = 0; previousIndex < result.length; previousIndex++) {
const previousType = result[previousIndex];
if (previousType.tag === currentType.tag &&
previousType.kind === currentType.kind) {
exclude.push(previousIndex);
}
}
result.push(currentType);
}
return result.filter((_type, index) => !exclude.includes(index));
}
function compileMap(...typesList) {
const result = {
fallback: {},
mapping: {},
scalar: {},
sequence: {},
};
for (const types of typesList) {
for (const type of types) {
if (type.kind !== null) {
result[type.kind][type.tag] = result["fallback"][type.tag] = type;
}
}
}
return result;
}
class Schema {
constructor(definition) {
Object.defineProperty(this, "implicit", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "explicit", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "include", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "compiledImplicit", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "compiledExplicit", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "compiledTypeMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.explicit = definition.explicit || [];
this.implicit = definition.implicit || [];
this.include = definition.include || [];
for (const type of this.implicit) {
if (type.loadKind && type.loadKind !== "scalar") {
throw new error_js_1.YAMLError("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
}
}
this.compiledImplicit = compileList(this, "implicit", []);
this.compiledExplicit = compileList(this, "explicit", []);
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
}
/* Returns a new extended schema from current schema */
extend(definition) {
return new Schema({
implicit: [
...new Set([...this.implicit, ...(definition?.implicit ?? [])]),
],
explicit: [
...new Set([...this.explicit, ...(definition?.explicit ?? [])]),
],
include: [...new Set([...this.include, ...(definition?.include ?? [])])],
});
}
static create() { }
}
exports.Schema = Schema;

View File

@@ -0,0 +1,14 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.core = void 0;
const schema_js_1 = require("../schema.js");
const json_js_1 = require("./json.js");
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
exports.core = new schema_js_1.Schema({
include: [json_js_1.json],
});

View File

@@ -0,0 +1,17 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.def = void 0;
const schema_js_1 = require("../schema.js");
const mod_js_1 = require("../type/mod.js");
const core_js_1 = require("./core.js");
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
exports.def = new schema_js_1.Schema({
explicit: [mod_js_1.binary, mod_js_1.omap, mod_js_1.pairs, mod_js_1.set],
implicit: [mod_js_1.timestamp, mod_js_1.merge],
include: [core_js_1.core],
});

View File

@@ -0,0 +1,13 @@
"use strict";
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extended = void 0;
const schema_js_1 = require("../schema.js");
const mod_js_1 = require("../type/mod.js");
const default_js_1 = require("./default.js");
// Extends JS-YAML default schema with additional JavaScript types
// It is not described in the YAML specification.
exports.extended = new schema_js_1.Schema({
explicit: [mod_js_1.regexp, mod_js_1.undefinedType],
include: [default_js_1.def],
});

View File

@@ -0,0 +1,14 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.failsafe = void 0;
const schema_js_1 = require("../schema.js");
const mod_js_1 = require("../type/mod.js");
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
exports.failsafe = new schema_js_1.Schema({
explicit: [mod_js_1.str, mod_js_1.seq, mod_js_1.map],
});

View File

@@ -0,0 +1,16 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.json = void 0;
const schema_js_1 = require("../schema.js");
const mod_js_1 = require("../type/mod.js");
const failsafe_js_1 = require("./failsafe.js");
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
exports.json = new schema_js_1.Schema({
implicit: [mod_js_1.nil, mod_js_1.bool, mod_js_1.int, mod_js_1.float],
include: [failsafe_js_1.failsafe],
});

View File

@@ -0,0 +1,17 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSON_SCHEMA = exports.FAILSAFE_SCHEMA = exports.EXTENDED_SCHEMA = exports.DEFAULT_SCHEMA = exports.CORE_SCHEMA = void 0;
var core_js_1 = require("./core.js");
Object.defineProperty(exports, "CORE_SCHEMA", { enumerable: true, get: function () { return core_js_1.core; } });
var default_js_1 = require("./default.js");
Object.defineProperty(exports, "DEFAULT_SCHEMA", { enumerable: true, get: function () { return default_js_1.def; } });
var extended_js_1 = require("./extended.js");
Object.defineProperty(exports, "EXTENDED_SCHEMA", { enumerable: true, get: function () { return extended_js_1.extended; } });
var failsafe_js_1 = require("./failsafe.js");
Object.defineProperty(exports, "FAILSAFE_SCHEMA", { enumerable: true, get: function () { return failsafe_js_1.failsafe; } });
var json_js_1 = require("./json.js");
Object.defineProperty(exports, "JSON_SCHEMA", { enumerable: true, get: function () { return json_js_1.json; } });

View File

@@ -0,0 +1,19 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.State = void 0;
const mod_js_1 = require("./schema/mod.js");
class State {
constructor(schema = mod_js_1.DEFAULT_SCHEMA) {
Object.defineProperty(this, "schema", {
enumerable: true,
configurable: true,
writable: true,
value: schema
});
}
}
exports.State = State;

View File

@@ -0,0 +1,17 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringify = void 0;
const dumper_js_1 = require("./dumper/dumper.js");
/**
* Serializes `object` as a YAML document.
*
* You can disable exceptions by setting the skipInvalid option to true.
*/
function stringify(obj, options) {
return (0, dumper_js_1.dump)(obj, options);
}
exports.stringify = stringify;

View File

@@ -0,0 +1,88 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Type = void 0;
const DEFAULT_RESOLVE = () => true;
const DEFAULT_CONSTRUCT = (data) => data;
function checkTagFormat(tag) {
return tag;
}
class Type {
constructor(tag, options) {
Object.defineProperty(this, "tag", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "kind", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "instanceOf", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "predicate", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "represent", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "defaultStyle", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "styleAliases", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "loadKind", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "resolve", {
enumerable: true,
configurable: true,
writable: true,
value: () => true
});
Object.defineProperty(this, "construct", {
enumerable: true,
configurable: true,
writable: true,
value: (data) => data
});
this.tag = checkTagFormat(tag);
if (options) {
this.kind = options.kind;
this.resolve = options.resolve || DEFAULT_RESOLVE;
this.construct = options.construct || DEFAULT_CONSTRUCT;
this.instanceOf = options.instanceOf;
this.predicate = options.predicate;
this.represent = options.represent;
this.defaultStyle = options.defaultStyle;
this.styleAliases = options.styleAliases;
}
}
}
exports.Type = Type;

View File

@@ -0,0 +1,122 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.binary = void 0;
// Ported from js-yaml v3.13.1:
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
const type_js_1 = require("../type.js");
const buffer_js_1 = require("../../../io/buffer.js");
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary(data) {
if (data === null)
return false;
let code;
let bitlen = 0;
const max = data.length;
const map = BASE64_MAP;
// Convert one by one.
for (let idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx));
// Skip CR/LF
if (code > 64)
continue;
// Fail on illegal characters
if (code < 0)
return false;
bitlen += 6;
}
// If there are any bits left, source was corrupted
return bitlen % 8 === 0;
}
function constructYamlBinary(data) {
// remove CR/LF & padding to simplify scan
const input = data.replace(/[\r\n=]/g, "");
const max = input.length;
const map = BASE64_MAP;
// Collect by 6*4 bits (3 bytes)
const result = [];
let bits = 0;
for (let idx = 0; idx < max; idx++) {
if (idx % 4 === 0 && idx) {
result.push((bits >> 16) & 0xff);
result.push((bits >> 8) & 0xff);
result.push(bits & 0xff);
}
bits = (bits << 6) | map.indexOf(input.charAt(idx));
}
// Dump tail
const tailbits = (max % 4) * 6;
if (tailbits === 0) {
result.push((bits >> 16) & 0xff);
result.push((bits >> 8) & 0xff);
result.push(bits & 0xff);
}
else if (tailbits === 18) {
result.push((bits >> 10) & 0xff);
result.push((bits >> 2) & 0xff);
}
else if (tailbits === 12) {
result.push((bits >> 4) & 0xff);
}
return new buffer_js_1.Buffer(new Uint8Array(result));
}
function representYamlBinary(object) {
const max = object.length;
const map = BASE64_MAP;
// Convert every three bytes to 4 ASCII characters.
let result = "";
let bits = 0;
for (let idx = 0; idx < max; idx++) {
if (idx % 3 === 0 && idx) {
result += map[(bits >> 18) & 0x3f];
result += map[(bits >> 12) & 0x3f];
result += map[(bits >> 6) & 0x3f];
result += map[bits & 0x3f];
}
bits = (bits << 8) + object[idx];
}
// Dump tail
const tail = max % 3;
if (tail === 0) {
result += map[(bits >> 18) & 0x3f];
result += map[(bits >> 12) & 0x3f];
result += map[(bits >> 6) & 0x3f];
result += map[bits & 0x3f];
}
else if (tail === 2) {
result += map[(bits >> 10) & 0x3f];
result += map[(bits >> 4) & 0x3f];
result += map[(bits << 2) & 0x3f];
result += map[64];
}
else if (tail === 1) {
result += map[(bits >> 2) & 0x3f];
result += map[(bits << 4) & 0x3f];
result += map[64];
result += map[64];
}
return result;
}
function isBinary(obj) {
const buf = new buffer_js_1.Buffer();
try {
if (0 > buf.readFromSync(obj))
return true;
return false;
}
catch {
return false;
}
finally {
buf.reset();
}
}
exports.binary = new type_js_1.Type("tag:yaml.org,2002:binary", {
construct: constructYamlBinary,
kind: "scalar",
predicate: isBinary,
represent: representYamlBinary,
resolve: resolveYamlBinary,
});

View File

@@ -0,0 +1,35 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.bool = void 0;
const type_js_1 = require("../type.js");
const utils_js_1 = require("../utils.js");
function resolveYamlBoolean(data) {
const max = data.length;
return ((max === 4 && (data === "true" || data === "True" || data === "TRUE")) ||
(max === 5 && (data === "false" || data === "False" || data === "FALSE")));
}
function constructYamlBoolean(data) {
return data === "true" || data === "True" || data === "TRUE";
}
exports.bool = new type_js_1.Type("tag:yaml.org,2002:bool", {
construct: constructYamlBoolean,
defaultStyle: "lowercase",
kind: "scalar",
predicate: utils_js_1.isBoolean,
represent: {
lowercase(object) {
return object ? "true" : "false";
},
uppercase(object) {
return object ? "TRUE" : "FALSE";
},
camelcase(object) {
return object ? "True" : "False";
},
},
resolve: resolveYamlBoolean,
});

View File

@@ -0,0 +1,109 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.float = void 0;
const type_js_1 = require("../type.js");
const utils_js_1 = require("../utils.js");
const YAML_FLOAT_PATTERN = new RegExp(
// 2.5e4, 2.5 and integers
"^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" +
// .2e4, .2
// special case, seems not from spec
"|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" +
// 20:59
"|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*" +
// .inf
"|[-+]?\\.(?:inf|Inf|INF)" +
// .nan
"|\\.(?:nan|NaN|NAN))$");
function resolveYamlFloat(data) {
if (!YAML_FLOAT_PATTERN.test(data) ||
// Quick hack to not allow integers end with `_`
// Probably should update regexp & check speed
data[data.length - 1] === "_") {
return false;
}
return true;
}
function constructYamlFloat(data) {
let value = data.replace(/_/g, "").toLowerCase();
const sign = value[0] === "-" ? -1 : 1;
const digits = [];
if ("+-".indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === ".inf") {
return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
}
if (value === ".nan") {
return NaN;
}
if (value.indexOf(":") >= 0) {
value.split(":").forEach((v) => {
digits.unshift(parseFloat(v));
});
let valueNb = 0.0;
let base = 1;
digits.forEach((d) => {
valueNb += d * base;
base *= 60;
});
return sign * valueNb;
}
return sign * parseFloat(value);
}
const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
if (isNaN(object)) {
switch (style) {
case "lowercase":
return ".nan";
case "uppercase":
return ".NAN";
case "camelcase":
return ".NaN";
}
}
else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return ".inf";
case "uppercase":
return ".INF";
case "camelcase":
return ".Inf";
}
}
else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return "-.inf";
case "uppercase":
return "-.INF";
case "camelcase":
return "-.Inf";
}
}
else if ((0, utils_js_1.isNegativeZero)(object)) {
return "-0.0";
}
const res = object.toString(10);
// JS stringifier can build scientific format without dots: 5e-100,
// while YAML requires dot: 5.e-100. Fix it with simple hack
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}
function isFloat(object) {
return (Object.prototype.toString.call(object) === "[object Number]" &&
(object % 1 !== 0 || (0, utils_js_1.isNegativeZero)(object)));
}
exports.float = new type_js_1.Type("tag:yaml.org,2002:float", {
construct: constructYamlFloat,
defaultStyle: "lowercase",
kind: "scalar",
predicate: isFloat,
represent: representYamlFloat,
resolve: resolveYamlFloat,
});

View File

@@ -0,0 +1,41 @@
"use strict";
// Ported and adapted from js-yaml-js-types v1.0.0:
// https://github.com/nodeca/js-yaml-js-types/tree/ac537e7bbdd3c2cbbd9882ca3919c520c2dc022b
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.func = void 0;
const type_js_1 = require("../type.js");
// Note: original implementation used Esprima to handle functions
// To avoid dependencies, we'll just try to check if we can construct a function from given string
function reconstructFunction(code) {
const func = new Function(`return ${code}`)();
if (!(func instanceof Function)) {
throw new TypeError(`Expected function but got ${typeof func}: ${code}`);
}
return func;
}
exports.func = new type_js_1.Type("tag:yaml.org,2002:js/function", {
kind: "scalar",
resolve(data) {
if (data === null) {
return false;
}
try {
reconstructFunction(`${data}`);
return true;
}
catch (_err) {
return false;
}
},
construct(data) {
return reconstructFunction(data);
},
predicate(object) {
return object instanceof Function;
},
represent(object) {
return object.toString();
},
});

View File

@@ -0,0 +1,171 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.int = void 0;
const type_js_1 = require("../type.js");
const utils_js_1 = require("../utils.js");
function isHexCode(c) {
return ((0x30 <= /* 0 */ c && c <= 0x39) /* 9 */ ||
(0x41 <= /* A */ c && c <= 0x46) /* F */ ||
(0x61 <= /* a */ c && c <= 0x66) /* f */);
}
function isOctCode(c) {
return 0x30 <= /* 0 */ c && c <= 0x37 /* 7 */;
}
function isDecCode(c) {
return 0x30 <= /* 0 */ c && c <= 0x39 /* 9 */;
}
function resolveYamlInteger(data) {
const max = data.length;
let index = 0;
let hasDigits = false;
if (!max)
return false;
let ch = data[index];
// sign
if (ch === "-" || ch === "+") {
ch = data[++index];
}
if (ch === "0") {
// 0
if (index + 1 === max)
return true;
ch = data[++index];
// base 2, base 8, base 16
if (ch === "b") {
// base 2
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === "_")
continue;
if (ch !== "0" && ch !== "1")
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
if (ch === "x") {
// base 16
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === "_")
continue;
if (!isHexCode(data.charCodeAt(index)))
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
// base 8
for (; index < max; index++) {
ch = data[index];
if (ch === "_")
continue;
if (!isOctCode(data.charCodeAt(index)))
return false;
hasDigits = true;
}
return hasDigits && ch !== "_";
}
// base 10 (except 0) or base 60
// value should not start with `_`;
if (ch === "_")
return false;
for (; index < max; index++) {
ch = data[index];
if (ch === "_")
continue;
if (ch === ":")
break;
if (!isDecCode(data.charCodeAt(index))) {
return false;
}
hasDigits = true;
}
// Should have digits and should not end with `_`
if (!hasDigits || ch === "_")
return false;
// if !base60 - done;
if (ch !== ":")
return true;
// base60 almost not used, no needs to optimize
return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
function constructYamlInteger(data) {
let value = data;
const digits = [];
if (value.indexOf("_") !== -1) {
value = value.replace(/_/g, "");
}
let sign = 1;
let ch = value[0];
if (ch === "-" || ch === "+") {
if (ch === "-")
sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === "0")
return 0;
if (ch === "0") {
if (value[1] === "b")
return sign * parseInt(value.slice(2), 2);
if (value[1] === "x")
return sign * parseInt(value, 16);
return sign * parseInt(value, 8);
}
if (value.indexOf(":") !== -1) {
value.split(":").forEach((v) => {
digits.unshift(parseInt(v, 10));
});
let valueInt = 0;
let base = 1;
digits.forEach((d) => {
valueInt += d * base;
base *= 60;
});
return sign * valueInt;
}
return sign * parseInt(value, 10);
}
function isInteger(object) {
return (Object.prototype.toString.call(object) === "[object Number]" &&
object % 1 === 0 &&
!(0, utils_js_1.isNegativeZero)(object));
}
exports.int = new type_js_1.Type("tag:yaml.org,2002:int", {
construct: constructYamlInteger,
defaultStyle: "decimal",
kind: "scalar",
predicate: isInteger,
represent: {
binary(obj) {
return obj >= 0
? `0b${obj.toString(2)}`
: `-0b${obj.toString(2).slice(1)}`;
},
octal(obj) {
return obj >= 0 ? `0${obj.toString(8)}` : `-0${obj.toString(8).slice(1)}`;
},
decimal(obj) {
return obj.toString(10);
},
hexadecimal(obj) {
return obj >= 0
? `0x${obj.toString(16).toUpperCase()}`
: `-0x${obj.toString(16).toUpperCase().slice(1)}`;
},
},
resolve: resolveYamlInteger,
styleAliases: {
binary: [2, "bin"],
decimal: [10, "dec"],
hexadecimal: [16, "hex"],
octal: [8, "oct"],
},
});

View File

@@ -0,0 +1,14 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.map = void 0;
const type_js_1 = require("../type.js");
exports.map = new type_js_1.Type("tag:yaml.org,2002:map", {
construct(data) {
return data !== null ? data : {};
},
kind: "mapping",
});

View File

@@ -0,0 +1,15 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.merge = void 0;
const type_js_1 = require("../type.js");
function resolveYamlMerge(data) {
return data === "<<" || data === null;
}
exports.merge = new type_js_1.Type("tag:yaml.org,2002:merge", {
kind: "scalar",
resolve: resolveYamlMerge,
});

View File

@@ -0,0 +1,39 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.undefinedType = exports.timestamp = exports.str = exports.set = exports.seq = exports.regexp = exports.pairs = exports.omap = exports.nil = exports.merge = exports.map = exports.int = exports.func = exports.float = exports.bool = exports.binary = void 0;
var binary_js_1 = require("./binary.js");
Object.defineProperty(exports, "binary", { enumerable: true, get: function () { return binary_js_1.binary; } });
var bool_js_1 = require("./bool.js");
Object.defineProperty(exports, "bool", { enumerable: true, get: function () { return bool_js_1.bool; } });
var float_js_1 = require("./float.js");
Object.defineProperty(exports, "float", { enumerable: true, get: function () { return float_js_1.float; } });
var function_js_1 = require("./function.js");
Object.defineProperty(exports, "func", { enumerable: true, get: function () { return function_js_1.func; } });
var int_js_1 = require("./int.js");
Object.defineProperty(exports, "int", { enumerable: true, get: function () { return int_js_1.int; } });
var map_js_1 = require("./map.js");
Object.defineProperty(exports, "map", { enumerable: true, get: function () { return map_js_1.map; } });
var merge_js_1 = require("./merge.js");
Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return merge_js_1.merge; } });
var nil_js_1 = require("./nil.js");
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return nil_js_1.nil; } });
var omap_js_1 = require("./omap.js");
Object.defineProperty(exports, "omap", { enumerable: true, get: function () { return omap_js_1.omap; } });
var pairs_js_1 = require("./pairs.js");
Object.defineProperty(exports, "pairs", { enumerable: true, get: function () { return pairs_js_1.pairs; } });
var regexp_js_1 = require("./regexp.js");
Object.defineProperty(exports, "regexp", { enumerable: true, get: function () { return regexp_js_1.regexp; } });
var seq_js_1 = require("./seq.js");
Object.defineProperty(exports, "seq", { enumerable: true, get: function () { return seq_js_1.seq; } });
var set_js_1 = require("./set.js");
Object.defineProperty(exports, "set", { enumerable: true, get: function () { return set_js_1.set; } });
var str_js_1 = require("./str.js");
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return str_js_1.str; } });
var timestamp_js_1 = require("./timestamp.js");
Object.defineProperty(exports, "timestamp", { enumerable: true, get: function () { return timestamp_js_1.timestamp; } });
var undefined_js_1 = require("./undefined.js");
Object.defineProperty(exports, "undefinedType", { enumerable: true, get: function () { return undefined_js_1.undefinedType; } });

View File

@@ -0,0 +1,40 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.nil = void 0;
const type_js_1 = require("../type.js");
function resolveYamlNull(data) {
const max = data.length;
return ((max === 1 && data === "~") ||
(max === 4 && (data === "null" || data === "Null" || data === "NULL")));
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return object === null;
}
exports.nil = new type_js_1.Type("tag:yaml.org,2002:null", {
construct: constructYamlNull,
defaultStyle: "lowercase",
kind: "scalar",
predicate: isNull,
represent: {
canonical() {
return "~";
},
lowercase() {
return "null";
},
uppercase() {
return "NULL";
},
camelcase() {
return "Null";
},
},
resolve: resolveYamlNull,
});

View File

@@ -0,0 +1,43 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.omap = void 0;
const type_js_1 = require("../type.js");
const { hasOwn } = Object;
const _toString = Object.prototype.toString;
function resolveYamlOmap(data) {
const objectKeys = [];
let pairKey = "";
let pairHasKey = false;
for (const pair of data) {
pairHasKey = false;
if (_toString.call(pair) !== "[object Object]")
return false;
for (pairKey in pair) {
if (hasOwn(pair, pairKey)) {
if (!pairHasKey)
pairHasKey = true;
else
return false;
}
}
if (!pairHasKey)
return false;
if (objectKeys.indexOf(pairKey) === -1)
objectKeys.push(pairKey);
else
return false;
}
return true;
}
function constructYamlOmap(data) {
return data !== null ? data : [];
}
exports.omap = new type_js_1.Type("tag:yaml.org,2002:omap", {
construct: constructYamlOmap,
kind: "sequence",
resolve: resolveYamlOmap,
});

View File

@@ -0,0 +1,38 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.pairs = void 0;
const type_js_1 = require("../type.js");
const _toString = Object.prototype.toString;
function resolveYamlPairs(data) {
const result = Array.from({ length: data.length });
for (let index = 0; index < data.length; index++) {
const pair = data[index];
if (_toString.call(pair) !== "[object Object]")
return false;
const keys = Object.keys(pair);
if (keys.length !== 1)
return false;
result[index] = [keys[0], pair[keys[0]]];
}
return true;
}
function constructYamlPairs(data) {
if (data === null)
return [];
const result = Array.from({ length: data.length });
for (let index = 0; index < data.length; index += 1) {
const pair = data[index];
const keys = Object.keys(pair);
result[index] = [keys[0], pair[keys[0]]];
}
return result;
}
exports.pairs = new type_js_1.Type("tag:yaml.org,2002:pairs", {
construct: constructYamlPairs,
kind: "sequence",
resolve: resolveYamlPairs,
});

View File

@@ -0,0 +1,40 @@
"use strict";
// Ported and adapted from js-yaml-js-types v1.0.0:
// https://github.com/nodeca/js-yaml-js-types/tree/ac537e7bbdd3c2cbbd9882ca3919c520c2dc022b
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexp = void 0;
const type_js_1 = require("../type.js");
const REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;
exports.regexp = new type_js_1.Type("tag:yaml.org,2002:js/regexp", {
kind: "scalar",
resolve(data) {
if ((data === null) || (!data.length)) {
return false;
}
const regexp = `${data}`;
if (regexp.charAt(0) === "/") {
// Ensure regex is properly terminated
if (!REGEXP.test(data)) {
return false;
}
// Check no duplicate modifiers
const modifiers = [...(regexp.match(REGEXP)?.groups?.modifiers ?? "")];
if (new Set(modifiers).size < modifiers.length) {
return false;
}
}
return true;
},
construct(data) {
const { regexp = `${data}`, modifiers = "" } = `${data}`.match(REGEXP)?.groups ?? {};
return new RegExp(regexp, modifiers);
},
predicate(object) {
return object instanceof RegExp;
},
represent(object) {
return object.toString();
},
});

View File

@@ -0,0 +1,14 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.seq = void 0;
const type_js_1 = require("../type.js");
exports.seq = new type_js_1.Type("tag:yaml.org,2002:seq", {
construct(data) {
return data !== null ? data : [];
},
kind: "sequence",
});

View File

@@ -0,0 +1,28 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.set = void 0;
const type_js_1 = require("../type.js");
const { hasOwn } = Object;
function resolveYamlSet(data) {
if (data === null)
return true;
for (const key in data) {
if (hasOwn(data, key)) {
if (data[key] !== null)
return false;
}
}
return true;
}
function constructYamlSet(data) {
return data !== null ? data : {};
}
exports.set = new type_js_1.Type("tag:yaml.org,2002:set", {
construct: constructYamlSet,
kind: "mapping",
resolve: resolveYamlSet,
});

View File

@@ -0,0 +1,13 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.str = void 0;
const type_js_1 = require("../type.js");
exports.str = new type_js_1.Type("tag:yaml.org,2002:str", {
construct(data) {
return data !== null ? data : "";
},
kind: "scalar",
});

View File

@@ -0,0 +1,81 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.timestamp = void 0;
const type_js_1 = require("../type.js");
const YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + // [1] year
"-([0-9][0-9])" + // [2] month
"-([0-9][0-9])$");
const YAML_TIMESTAMP_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + // [1] year
"-([0-9][0-9]?)" + // [2] month
"-([0-9][0-9]?)" + // [3] day
"(?:[Tt]|[ \\t]+)" + // ...
"([0-9][0-9]?)" + // [4] hour
":([0-9][0-9])" + // [5] minute
":([0-9][0-9])" + // [6] second
"(?:\\.([0-9]*))?" + // [7] fraction
"(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + // [8] tz [9] tz_sign [10] tz_hour
"(?::([0-9][0-9]))?))?$");
function resolveYamlTimestamp(data) {
if (data === null)
return false;
if (YAML_DATE_REGEXP.exec(data) !== null)
return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
return true;
return false;
}
function constructYamlTimestamp(data) {
let match = YAML_DATE_REGEXP.exec(data);
if (match === null)
match = YAML_TIMESTAMP_REGEXP.exec(data);
if (match === null)
throw new Error("Date resolve error");
// match: [1] year [2] month [3] day
const year = +match[1];
const month = +match[2] - 1; // JS month starts with 0
const day = +match[3];
if (!match[4]) {
// no hour
return new Date(Date.UTC(year, month, day));
}
// match: [4] hour [5] minute [6] second [7] fraction
const hour = +match[4];
const minute = +match[5];
const second = +match[6];
let fraction = 0;
if (match[7]) {
let partFraction = match[7].slice(0, 3);
while (partFraction.length < 3) {
// milli-seconds
partFraction += "0";
}
fraction = +partFraction;
}
// match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
let delta = null;
if (match[9]) {
const tzHour = +match[10];
const tzMinute = +(match[11] || 0);
delta = (tzHour * 60 + tzMinute) * 60000; // delta in milli-seconds
if (match[9] === "-")
delta = -delta;
}
const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta)
date.setTime(date.getTime() - delta);
return date;
}
function representYamlTimestamp(date) {
return date.toISOString();
}
exports.timestamp = new type_js_1.Type("tag:yaml.org,2002:timestamp", {
construct: constructYamlTimestamp,
instanceOf: Date,
kind: "scalar",
represent: representYamlTimestamp,
resolve: resolveYamlTimestamp,
});

View File

@@ -0,0 +1,23 @@
"use strict";
// Ported and adapted from js-yaml-js-types v1.0.0:
// https://github.com/nodeca/js-yaml-js-types/tree/ac537e7bbdd3c2cbbd9882ca3919c520c2dc022b
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.undefinedType = void 0;
const type_js_1 = require("../type.js");
exports.undefinedType = new type_js_1.Type("tag:yaml.org,2002:js/undefined", {
kind: "scalar",
resolve() {
return true;
},
construct() {
return undefined;
},
predicate(object) {
return typeof object === "undefined";
},
represent() {
return "";
},
});

View File

@@ -0,0 +1,75 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isNegativeZero = exports.repeat = exports.toArray = exports.isRegExp = exports.isFunction = exports.isError = exports.isObject = exports.isUndefined = exports.isSymbol = exports.isString = exports.isNumber = exports.isNull = exports.isBoolean = exports.isArray = exports.isNothing = void 0;
function isNothing(subject) {
return typeof subject === "undefined" || subject === null;
}
exports.isNothing = isNothing;
function isArray(value) {
return Array.isArray(value);
}
exports.isArray = isArray;
function isBoolean(value) {
return typeof value === "boolean" || value instanceof Boolean;
}
exports.isBoolean = isBoolean;
function isNull(value) {
return value === null;
}
exports.isNull = isNull;
function isNumber(value) {
return typeof value === "number" || value instanceof Number;
}
exports.isNumber = isNumber;
function isString(value) {
return typeof value === "string" || value instanceof String;
}
exports.isString = isString;
function isSymbol(value) {
return typeof value === "symbol";
}
exports.isSymbol = isSymbol;
function isUndefined(value) {
return value === undefined;
}
exports.isUndefined = isUndefined;
function isObject(value) {
return value !== null && typeof value === "object";
}
exports.isObject = isObject;
function isError(e) {
return e instanceof Error;
}
exports.isError = isError;
function isFunction(value) {
return typeof value === "function";
}
exports.isFunction = isFunction;
function isRegExp(value) {
return value instanceof RegExp;
}
exports.isRegExp = isRegExp;
function toArray(sequence) {
if (isArray(sequence))
return sequence;
if (isNothing(sequence))
return [];
return [sequence];
}
exports.toArray = toArray;
function repeat(str, count) {
let result = "";
for (let cycle = 0; cycle < count; cycle++) {
result += str;
}
return result;
}
exports.repeat = repeat;
function isNegativeZero(i) {
return i === 0 && Number.NEGATIVE_INFINITY === 1 / i;
}
exports.isNegativeZero = isNegativeZero;

View File

@@ -0,0 +1,20 @@
"use strict";
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSON_SCHEMA = exports.FAILSAFE_SCHEMA = exports.EXTENDED_SCHEMA = exports.DEFAULT_SCHEMA = exports.CORE_SCHEMA = exports.Type = exports.stringify = exports.parseAll = exports.parse = void 0;
var parse_js_1 = require("./_yaml/parse.js");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parse_js_1.parse; } });
Object.defineProperty(exports, "parseAll", { enumerable: true, get: function () { return parse_js_1.parseAll; } });
var stringify_js_1 = require("./_yaml/stringify.js");
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return stringify_js_1.stringify; } });
var type_js_1 = require("./_yaml/type.js");
Object.defineProperty(exports, "Type", { enumerable: true, get: function () { return type_js_1.Type; } });
var mod_js_1 = require("./_yaml/schema/mod.js");
Object.defineProperty(exports, "CORE_SCHEMA", { enumerable: true, get: function () { return mod_js_1.CORE_SCHEMA; } });
Object.defineProperty(exports, "DEFAULT_SCHEMA", { enumerable: true, get: function () { return mod_js_1.DEFAULT_SCHEMA; } });
Object.defineProperty(exports, "EXTENDED_SCHEMA", { enumerable: true, get: function () { return mod_js_1.EXTENDED_SCHEMA; } });
Object.defineProperty(exports, "FAILSAFE_SCHEMA", { enumerable: true, get: function () { return mod_js_1.FAILSAFE_SCHEMA; } });
Object.defineProperty(exports, "JSON_SCHEMA", { enumerable: true, get: function () { return mod_js_1.JSON_SCHEMA; } });

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,501 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stripColor = exports.bgRgb24 = exports.rgb24 = exports.bgRgb8 = exports.rgb8 = exports.bgBrightWhite = exports.bgBrightCyan = exports.bgBrightMagenta = exports.bgBrightBlue = exports.bgBrightYellow = exports.bgBrightGreen = exports.bgBrightRed = exports.bgBrightBlack = exports.bgWhite = exports.bgCyan = exports.bgMagenta = exports.bgBlue = exports.bgYellow = exports.bgGreen = exports.bgRed = exports.bgBlack = exports.brightWhite = exports.brightCyan = exports.brightMagenta = exports.brightBlue = exports.brightYellow = exports.brightGreen = exports.brightRed = exports.brightBlack = exports.gray = exports.white = exports.cyan = exports.magenta = exports.blue = exports.yellow = exports.green = exports.red = exports.black = exports.strikethrough = exports.hidden = exports.inverse = exports.underline = exports.italic = exports.dim = exports.bold = exports.reset = exports.getColorEnabled = exports.setColorEnabled = void 0;
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// A module to print ANSI terminal colors. Inspired by chalk, kleur, and colors
// on npm.
//
// ```
// import { bgBlue, red, bold } from "https://deno.land/std/fmt/colors.ts";
// console.log(bgBlue(red(bold("Hello world!"))));
// ```
//
// This module supports `NO_COLOR` environmental variable disabling any coloring
// if `NO_COLOR` is set.
//
// This module is browser compatible.
const dntShim = __importStar(require("../../../../_dnt.test_shims.js"));
const noColor = dntShim.dntGlobalThis.Deno?.noColor ?? true;
let enabled = !noColor;
/**
* Set changing text color to enabled or disabled
* @param value
*/
function setColorEnabled(value) {
if (noColor) {
return;
}
enabled = value;
}
exports.setColorEnabled = setColorEnabled;
/** Get whether text color change is enabled or disabled. */
function getColorEnabled() {
return enabled;
}
exports.getColorEnabled = getColorEnabled;
/**
* Builds color code
* @param open
* @param close
*/
function code(open, close) {
return {
open: `\x1b[${open.join(";")}m`,
close: `\x1b[${close}m`,
regexp: new RegExp(`\\x1b\\[${close}m`, "g"),
};
}
/**
* Applies color and background based on color code and its associated text
* @param str text to apply color settings to
* @param code color code to apply
*/
function run(str, code) {
return enabled
? `${code.open}${str.replace(code.regexp, code.open)}${code.close}`
: str;
}
/**
* Reset the text modified
* @param str text to reset
*/
function reset(str) {
return run(str, code([0], 0));
}
exports.reset = reset;
/**
* Make the text bold.
* @param str text to make bold
*/
function bold(str) {
return run(str, code([1], 22));
}
exports.bold = bold;
/**
* The text emits only a small amount of light.
* @param str text to dim
*/
function dim(str) {
return run(str, code([2], 22));
}
exports.dim = dim;
/**
* Make the text italic.
* @param str text to make italic
*/
function italic(str) {
return run(str, code([3], 23));
}
exports.italic = italic;
/**
* Make the text underline.
* @param str text to underline
*/
function underline(str) {
return run(str, code([4], 24));
}
exports.underline = underline;
/**
* Invert background color and text color.
* @param str text to invert its color
*/
function inverse(str) {
return run(str, code([7], 27));
}
exports.inverse = inverse;
/**
* Make the text hidden.
* @param str text to hide
*/
function hidden(str) {
return run(str, code([8], 28));
}
exports.hidden = hidden;
/**
* Put horizontal line through the center of the text.
* @param str text to strike through
*/
function strikethrough(str) {
return run(str, code([9], 29));
}
exports.strikethrough = strikethrough;
/**
* Set text color to black.
* @param str text to make black
*/
function black(str) {
return run(str, code([30], 39));
}
exports.black = black;
/**
* Set text color to red.
* @param str text to make red
*/
function red(str) {
return run(str, code([31], 39));
}
exports.red = red;
/**
* Set text color to green.
* @param str text to make green
*/
function green(str) {
return run(str, code([32], 39));
}
exports.green = green;
/**
* Set text color to yellow.
* @param str text to make yellow
*/
function yellow(str) {
return run(str, code([33], 39));
}
exports.yellow = yellow;
/**
* Set text color to blue.
* @param str text to make blue
*/
function blue(str) {
return run(str, code([34], 39));
}
exports.blue = blue;
/**
* Set text color to magenta.
* @param str text to make magenta
*/
function magenta(str) {
return run(str, code([35], 39));
}
exports.magenta = magenta;
/**
* Set text color to cyan.
* @param str text to make cyan
*/
function cyan(str) {
return run(str, code([36], 39));
}
exports.cyan = cyan;
/**
* Set text color to white.
* @param str text to make white
*/
function white(str) {
return run(str, code([37], 39));
}
exports.white = white;
/**
* Set text color to gray.
* @param str text to make gray
*/
function gray(str) {
return brightBlack(str);
}
exports.gray = gray;
/**
* Set text color to bright black.
* @param str text to make bright-black
*/
function brightBlack(str) {
return run(str, code([90], 39));
}
exports.brightBlack = brightBlack;
/**
* Set text color to bright red.
* @param str text to make bright-red
*/
function brightRed(str) {
return run(str, code([91], 39));
}
exports.brightRed = brightRed;
/**
* Set text color to bright green.
* @param str text to make bright-green
*/
function brightGreen(str) {
return run(str, code([92], 39));
}
exports.brightGreen = brightGreen;
/**
* Set text color to bright yellow.
* @param str text to make bright-yellow
*/
function brightYellow(str) {
return run(str, code([93], 39));
}
exports.brightYellow = brightYellow;
/**
* Set text color to bright blue.
* @param str text to make bright-blue
*/
function brightBlue(str) {
return run(str, code([94], 39));
}
exports.brightBlue = brightBlue;
/**
* Set text color to bright magenta.
* @param str text to make bright-magenta
*/
function brightMagenta(str) {
return run(str, code([95], 39));
}
exports.brightMagenta = brightMagenta;
/**
* Set text color to bright cyan.
* @param str text to make bright-cyan
*/
function brightCyan(str) {
return run(str, code([96], 39));
}
exports.brightCyan = brightCyan;
/**
* Set text color to bright white.
* @param str text to make bright-white
*/
function brightWhite(str) {
return run(str, code([97], 39));
}
exports.brightWhite = brightWhite;
/**
* Set background color to black.
* @param str text to make its background black
*/
function bgBlack(str) {
return run(str, code([40], 49));
}
exports.bgBlack = bgBlack;
/**
* Set background color to red.
* @param str text to make its background red
*/
function bgRed(str) {
return run(str, code([41], 49));
}
exports.bgRed = bgRed;
/**
* Set background color to green.
* @param str text to make its background green
*/
function bgGreen(str) {
return run(str, code([42], 49));
}
exports.bgGreen = bgGreen;
/**
* Set background color to yellow.
* @param str text to make its background yellow
*/
function bgYellow(str) {
return run(str, code([43], 49));
}
exports.bgYellow = bgYellow;
/**
* Set background color to blue.
* @param str text to make its background blue
*/
function bgBlue(str) {
return run(str, code([44], 49));
}
exports.bgBlue = bgBlue;
/**
* Set background color to magenta.
* @param str text to make its background magenta
*/
function bgMagenta(str) {
return run(str, code([45], 49));
}
exports.bgMagenta = bgMagenta;
/**
* Set background color to cyan.
* @param str text to make its background cyan
*/
function bgCyan(str) {
return run(str, code([46], 49));
}
exports.bgCyan = bgCyan;
/**
* Set background color to white.
* @param str text to make its background white
*/
function bgWhite(str) {
return run(str, code([47], 49));
}
exports.bgWhite = bgWhite;
/**
* Set background color to bright black.
* @param str text to make its background bright-black
*/
function bgBrightBlack(str) {
return run(str, code([100], 49));
}
exports.bgBrightBlack = bgBrightBlack;
/**
* Set background color to bright red.
* @param str text to make its background bright-red
*/
function bgBrightRed(str) {
return run(str, code([101], 49));
}
exports.bgBrightRed = bgBrightRed;
/**
* Set background color to bright green.
* @param str text to make its background bright-green
*/
function bgBrightGreen(str) {
return run(str, code([102], 49));
}
exports.bgBrightGreen = bgBrightGreen;
/**
* Set background color to bright yellow.
* @param str text to make its background bright-yellow
*/
function bgBrightYellow(str) {
return run(str, code([103], 49));
}
exports.bgBrightYellow = bgBrightYellow;
/**
* Set background color to bright blue.
* @param str text to make its background bright-blue
*/
function bgBrightBlue(str) {
return run(str, code([104], 49));
}
exports.bgBrightBlue = bgBrightBlue;
/**
* Set background color to bright magenta.
* @param str text to make its background bright-magenta
*/
function bgBrightMagenta(str) {
return run(str, code([105], 49));
}
exports.bgBrightMagenta = bgBrightMagenta;
/**
* Set background color to bright cyan.
* @param str text to make its background bright-cyan
*/
function bgBrightCyan(str) {
return run(str, code([106], 49));
}
exports.bgBrightCyan = bgBrightCyan;
/**
* Set background color to bright white.
* @param str text to make its background bright-white
*/
function bgBrightWhite(str) {
return run(str, code([107], 49));
}
exports.bgBrightWhite = bgBrightWhite;
/* Special Color Sequences */
/**
* Clam and truncate color codes
* @param n
* @param max number to truncate to
* @param min number to truncate from
*/
function clampAndTruncate(n, max = 255, min = 0) {
return Math.trunc(Math.max(Math.min(n, max), min));
}
/**
* Set text color using paletted 8bit colors.
* https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
* @param str text color to apply paletted 8bit colors to
* @param color code
*/
function rgb8(str, color) {
return run(str, code([38, 5, clampAndTruncate(color)], 39));
}
exports.rgb8 = rgb8;
/**
* Set background color using paletted 8bit colors.
* https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
* @param str text color to apply paletted 8bit background colors to
* @param color code
*/
function bgRgb8(str, color) {
return run(str, code([48, 5, clampAndTruncate(color)], 49));
}
exports.bgRgb8 = bgRgb8;
/**
* Set text color using 24bit rgb.
* `color` can be a number in range `0x000000` to `0xffffff` or
* an `Rgb`.
*
* To produce the color magenta:
*
* rgb24("foo", 0xff00ff);
* rgb24("foo", {r: 255, g: 0, b: 255});
* @param str text color to apply 24bit rgb to
* @param color code
*/
function rgb24(str, color) {
if (typeof color === "number") {
return run(str, code([38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 39));
}
return run(str, code([
38,
2,
clampAndTruncate(color.r),
clampAndTruncate(color.g),
clampAndTruncate(color.b),
], 39));
}
exports.rgb24 = rgb24;
/**
* Set background color using 24bit rgb.
* `color` can be a number in range `0x000000` to `0xffffff` or
* an `Rgb`.
*
* To produce the color magenta:
*
* bgRgb24("foo", 0xff00ff);
* bgRgb24("foo", {r: 255, g: 0, b: 255});
* @param str text color to apply 24bit rgb to
* @param color code
*/
function bgRgb24(str, color) {
if (typeof color === "number") {
return run(str, code([48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 49));
}
return run(str, code([
48,
2,
clampAndTruncate(color.r),
clampAndTruncate(color.g),
clampAndTruncate(color.b),
], 49));
}
exports.bgRgb24 = bgRgb24;
// https://github.com/chalk/ansi-regex/blob/2b56fb0c7a07108e5b54241e8faec160d393aedb/index.js
const ANSI_PATTERN = new RegExp([
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
].join("|"), "g");
/**
* Remove ANSI escape codes from the string.
* @param string to remove ANSI escape codes from
*/
function stripColor(string) {
return string.replace(ANSI_PATTERN, "");
}
exports.stripColor = stripColor;

View File

@@ -0,0 +1,164 @@
"use strict";
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.diff = exports.DiffType = void 0;
var DiffType;
(function (DiffType) {
DiffType["removed"] = "removed";
DiffType["common"] = "common";
DiffType["added"] = "added";
})(DiffType = exports.DiffType || (exports.DiffType = {}));
const REMOVED = 1;
const COMMON = 2;
const ADDED = 3;
function createCommon(A, B, reverse) {
const common = [];
if (A.length === 0 || B.length === 0)
return [];
for (let i = 0; i < Math.min(A.length, B.length); i += 1) {
if (A[reverse ? A.length - i - 1 : i] === B[reverse ? B.length - i - 1 : i]) {
common.push(A[reverse ? A.length - i - 1 : i]);
}
else {
return common;
}
}
return common;
}
/**
* Renders the differences between the actual and expected values
* @param A Actual value
* @param B Expected value
*/
function diff(A, B) {
const prefixCommon = createCommon(A, B);
const suffixCommon = createCommon(A.slice(prefixCommon.length), B.slice(prefixCommon.length), true).reverse();
A = suffixCommon.length
? A.slice(prefixCommon.length, -suffixCommon.length)
: A.slice(prefixCommon.length);
B = suffixCommon.length
? B.slice(prefixCommon.length, -suffixCommon.length)
: B.slice(prefixCommon.length);
const swapped = B.length > A.length;
[A, B] = swapped ? [B, A] : [A, B];
const M = A.length;
const N = B.length;
if (!M && !N && !suffixCommon.length && !prefixCommon.length)
return [];
if (!N) {
return [
...prefixCommon.map((c) => ({ type: DiffType.common, value: c })),
...A.map((a) => ({
type: swapped ? DiffType.added : DiffType.removed,
value: a,
})),
...suffixCommon.map((c) => ({ type: DiffType.common, value: c })),
];
}
const offset = N;
const delta = M - N;
const size = M + N + 1;
const fp = new Array(size).fill({ y: -1 });
/**
* INFO:
* This buffer is used to save memory and improve performance.
* The first half is used to save route and last half is used to save diff
* type.
* This is because, when I kept new uint8array area to save type,performance
* worsened.
*/
const routes = new Uint32Array((M * N + size + 1) * 2);
const diffTypesPtrOffset = routes.length / 2;
let ptr = 0;
let p = -1;
function backTrace(A, B, current, swapped) {
const M = A.length;
const N = B.length;
const result = [];
let a = M - 1;
let b = N - 1;
let j = routes[current.id];
let type = routes[current.id + diffTypesPtrOffset];
while (true) {
if (!j && !type)
break;
const prev = j;
if (type === REMOVED) {
result.unshift({
type: swapped ? DiffType.removed : DiffType.added,
value: B[b],
});
b -= 1;
}
else if (type === ADDED) {
result.unshift({
type: swapped ? DiffType.added : DiffType.removed,
value: A[a],
});
a -= 1;
}
else {
result.unshift({ type: DiffType.common, value: A[a] });
a -= 1;
b -= 1;
}
j = routes[prev];
type = routes[prev + diffTypesPtrOffset];
}
return result;
}
function createFP(slide, down, k, M) {
if (slide && slide.y === -1 && down && down.y === -1) {
return { y: 0, id: 0 };
}
if ((down && down.y === -1) ||
k === M ||
(slide && slide.y) > (down && down.y) + 1) {
const prev = slide.id;
ptr++;
routes[ptr] = prev;
routes[ptr + diffTypesPtrOffset] = ADDED;
return { y: slide.y, id: ptr };
}
else {
const prev = down.id;
ptr++;
routes[ptr] = prev;
routes[ptr + diffTypesPtrOffset] = REMOVED;
return { y: down.y + 1, id: ptr };
}
}
function snake(k, slide, down, _offset, A, B) {
const M = A.length;
const N = B.length;
if (k < -N || M < k)
return { y: -1, id: -1 };
const fp = createFP(slide, down, k, M);
while (fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]) {
const prev = fp.id;
ptr++;
fp.id = ptr;
fp.y += 1;
routes[ptr] = prev;
routes[ptr + diffTypesPtrOffset] = COMMON;
}
return fp;
}
while (fp[delta + offset].y < N) {
p = p + 1;
for (let k = -p; k < delta; ++k) {
fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B);
}
for (let k = delta + p; k > delta; --k) {
fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B);
}
fp[delta + offset] = snake(delta, fp[delta - 1 + offset], fp[delta + 1 + offset], offset, A, B);
}
return [
...prefixCommon.map((c) => ({ type: DiffType.common, value: c })),
...backTrace(A, B, fp[delta + offset], swapped),
...suffixCommon.map((c) => ({ type: DiffType.common, value: c })),
];
}
exports.diff = diff;

View File

@@ -0,0 +1,484 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.unreachable = exports.unimplemented = exports.assertThrowsAsync = exports.assertThrows = exports.fail = exports.assertObjectMatch = exports.assertNotMatch = exports.assertMatch = exports.assertArrayIncludes = exports.assertStringIncludes = exports.assertExists = exports.assertNotStrictEquals = exports.assertStrictEquals = exports.assertNotEquals = exports.assertEquals = exports.assert = exports.equal = exports._format = exports.AssertionError = void 0;
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible. Do not rely on good formatting of values
// for AssertionError messages in browsers.
const dntShim = __importStar(require("../../../../_dnt.test_shims.js"));
const colors_js_1 = require("../fmt/colors.js");
const _diff_js_1 = require("./_diff.js");
const CAN_NOT_DISPLAY = "[Cannot display]";
class AssertionError extends Error {
constructor(message) {
super(message);
this.name = "AssertionError";
}
}
exports.AssertionError = AssertionError;
/**
* Converts the input into a string. Objects, Sets and Maps are sorted so as to
* make tests less flaky
* @param v Value to be formatted
*/
function _format(v) {
return dntShim.dntGlobalThis.Deno
? dntShim.Deno.inspect(v, {
depth: Infinity,
sorted: true,
trailingComma: true,
compact: false,
iterableLimit: Infinity,
})
: `"${String(v).replace(/(?=["\\])/g, "\\")}"`;
}
exports._format = _format;
/**
* Colors the output of assertion diffs
* @param diffType Difference type, either added or removed
*/
function createColor(diffType) {
switch (diffType) {
case _diff_js_1.DiffType.added:
return (s) => (0, colors_js_1.green)((0, colors_js_1.bold)(s));
case _diff_js_1.DiffType.removed:
return (s) => (0, colors_js_1.red)((0, colors_js_1.bold)(s));
default:
return colors_js_1.white;
}
}
/**
* Prefixes `+` or `-` in diff output
* @param diffType Difference type, either added or removed
*/
function createSign(diffType) {
switch (diffType) {
case _diff_js_1.DiffType.added:
return "+ ";
case _diff_js_1.DiffType.removed:
return "- ";
default:
return " ";
}
}
function buildMessage(diffResult) {
const messages = [];
messages.push("");
messages.push("");
messages.push(` ${(0, colors_js_1.gray)((0, colors_js_1.bold)("[Diff]"))} ${(0, colors_js_1.red)((0, colors_js_1.bold)("Actual"))} / ${(0, colors_js_1.green)((0, colors_js_1.bold)("Expected"))}`);
messages.push("");
messages.push("");
diffResult.forEach((result) => {
const c = createColor(result.type);
messages.push(c(`${createSign(result.type)}${result.value}`));
});
messages.push("");
return messages;
}
function isKeyedCollection(x) {
return [Symbol.iterator, "size"].every((k) => k in x);
}
/**
* Deep equality comparison used in assertions
* @param c actual value
* @param d expected value
*/
function equal(c, d) {
const seen = new Map();
return (function compare(a, b) {
// Have to render RegExp & Date for string comparison
// unless it's mistreated as object
if (a &&
b &&
((a instanceof RegExp && b instanceof RegExp) ||
(a instanceof URL && b instanceof URL))) {
return String(a) === String(b);
}
if (a instanceof Date && b instanceof Date) {
const aTime = a.getTime();
const bTime = b.getTime();
// Check for NaN equality manually since NaN is not
// equal to itself.
if (Number.isNaN(aTime) && Number.isNaN(bTime)) {
return true;
}
return a.getTime() === b.getTime();
}
if (Object.is(a, b)) {
return true;
}
if (a && typeof a === "object" && b && typeof b === "object") {
if (seen.get(a) === b) {
return true;
}
if (Object.keys(a || {}).length !== Object.keys(b || {}).length) {
return false;
}
if (isKeyedCollection(a) && isKeyedCollection(b)) {
if (a.size !== b.size) {
return false;
}
let unmatchedEntries = a.size;
for (const [aKey, aValue] of a.entries()) {
for (const [bKey, bValue] of b.entries()) {
/* Given that Map keys can be references, we need
* to ensure that they are also deeply equal */
if ((aKey === aValue && bKey === bValue && compare(aKey, bKey)) ||
(compare(aKey, bKey) && compare(aValue, bValue))) {
unmatchedEntries--;
}
}
}
return unmatchedEntries === 0;
}
const merged = { ...a, ...b };
for (const key of [
...Object.getOwnPropertyNames(merged),
...Object.getOwnPropertySymbols(merged),
]) {
if (!compare(a && a[key], b && b[key])) {
return false;
}
if (((key in a) && (!(key in b))) || ((key in b) && (!(key in a)))) {
return false;
}
}
seen.set(a, b);
return true;
}
return false;
})(c, d);
}
exports.equal = equal;
/** Make an assertion, error will be thrown if `expr` does not have truthy value. */
function assert(expr, msg = "") {
if (!expr) {
throw new AssertionError(msg);
}
}
exports.assert = assert;
function assertEquals(actual, expected, msg) {
if (equal(actual, expected)) {
return;
}
let message = "";
const actualString = _format(actual);
const expectedString = _format(expected);
try {
const diffResult = (0, _diff_js_1.diff)(actualString.split("\n"), expectedString.split("\n"));
const diffMsg = buildMessage(diffResult).join("\n");
message = `Values are not equal:\n${diffMsg}`;
}
catch {
message = `\n${(0, colors_js_1.red)(CAN_NOT_DISPLAY)} + \n\n`;
}
if (msg) {
message = msg;
}
throw new AssertionError(message);
}
exports.assertEquals = assertEquals;
function assertNotEquals(actual, expected, msg) {
if (!equal(actual, expected)) {
return;
}
let actualString;
let expectedString;
try {
actualString = String(actual);
}
catch {
actualString = "[Cannot display]";
}
try {
expectedString = String(expected);
}
catch {
expectedString = "[Cannot display]";
}
if (!msg) {
msg = `actual: ${actualString} expected: ${expectedString}`;
}
throw new AssertionError(msg);
}
exports.assertNotEquals = assertNotEquals;
function assertStrictEquals(actual, expected, msg) {
if (actual === expected) {
return;
}
let message;
if (msg) {
message = msg;
}
else {
const actualString = _format(actual);
const expectedString = _format(expected);
if (actualString === expectedString) {
const withOffset = actualString
.split("\n")
.map((l) => ` ${l}`)
.join("\n");
message =
`Values have the same structure but are not reference-equal:\n\n${(0, colors_js_1.red)(withOffset)}\n`;
}
else {
try {
const diffResult = (0, _diff_js_1.diff)(actualString.split("\n"), expectedString.split("\n"));
const diffMsg = buildMessage(diffResult).join("\n");
message = `Values are not strictly equal:\n${diffMsg}`;
}
catch {
message = `\n${(0, colors_js_1.red)(CAN_NOT_DISPLAY)} + \n\n`;
}
}
}
throw new AssertionError(message);
}
exports.assertStrictEquals = assertStrictEquals;
function assertNotStrictEquals(actual, expected, msg) {
if (actual !== expected) {
return;
}
throw new AssertionError(msg ?? `Expected "actual" to be strictly unequal to: ${_format(actual)}\n`);
}
exports.assertNotStrictEquals = assertNotStrictEquals;
/**
* Make an assertion that actual is not null or undefined. If not
* then thrown.
*/
function assertExists(actual, msg) {
if (actual === undefined || actual === null) {
if (!msg) {
msg =
`actual: "${actual}" expected to match anything but null or undefined`;
}
throw new AssertionError(msg);
}
}
exports.assertExists = assertExists;
/**
* Make an assertion that actual includes expected. If not
* then thrown.
*/
function assertStringIncludes(actual, expected, msg) {
if (!actual.includes(expected)) {
if (!msg) {
msg = `actual: "${actual}" expected to contain: "${expected}"`;
}
throw new AssertionError(msg);
}
}
exports.assertStringIncludes = assertStringIncludes;
function assertArrayIncludes(actual, expected, msg) {
const missing = [];
for (let i = 0; i < expected.length; i++) {
let found = false;
for (let j = 0; j < actual.length; j++) {
if (equal(expected[i], actual[j])) {
found = true;
break;
}
}
if (!found) {
missing.push(expected[i]);
}
}
if (missing.length === 0) {
return;
}
if (!msg) {
msg = `actual: "${_format(actual)}" expected to include: "${_format(expected)}"\nmissing: ${_format(missing)}`;
}
throw new AssertionError(msg);
}
exports.assertArrayIncludes = assertArrayIncludes;
/**
* Make an assertion that `actual` match RegExp `expected`. If not
* then thrown
*/
function assertMatch(actual, expected, msg) {
if (!expected.test(actual)) {
if (!msg) {
msg = `actual: "${actual}" expected to match: "${expected}"`;
}
throw new AssertionError(msg);
}
}
exports.assertMatch = assertMatch;
/**
* Make an assertion that `actual` not match RegExp `expected`. If match
* then thrown
*/
function assertNotMatch(actual, expected, msg) {
if (expected.test(actual)) {
if (!msg) {
msg = `actual: "${actual}" expected to not match: "${expected}"`;
}
throw new AssertionError(msg);
}
}
exports.assertNotMatch = assertNotMatch;
/**
* Make an assertion that `actual` object is a subset of `expected` object, deeply.
* If not, then throw.
*/
function assertObjectMatch(
// deno-lint-ignore no-explicit-any
actual, expected) {
const seen = new WeakMap();
return assertEquals((function filter(a, b) {
// Prevent infinite loop with circular references with same filter
if ((seen.has(a)) && (seen.get(a) === b)) {
return a;
}
seen.set(a, b);
// Filter keys and symbols which are present in both actual and expected
const filtered = {};
const entries = [
...Object.getOwnPropertyNames(a),
...Object.getOwnPropertySymbols(a),
]
.filter((key) => key in b)
.map((key) => [key, a[key]]);
for (const [key, value] of entries) {
// On array references, build a filtered array and filter nested objects inside
if (Array.isArray(value)) {
const subset = b[key];
if (Array.isArray(subset)) {
filtered[key] = value
.slice(0, subset.length)
.map((element, index) => {
const subsetElement = subset[index];
if ((typeof subsetElement === "object") && (subsetElement)) {
return filter(element, subsetElement);
}
return element;
});
continue;
}
} // On nested objects references, build a filtered object recursively
else if (typeof value === "object") {
const subset = b[key];
if ((typeof subset === "object") && (subset)) {
filtered[key] = filter(value, subset);
continue;
}
}
filtered[key] = value;
}
return filtered;
})(actual, expected), expected);
}
exports.assertObjectMatch = assertObjectMatch;
/**
* Forcefully throws a failed assertion
*/
function fail(msg) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`);
}
exports.fail = fail;
/**
* Executes a function, expecting it to throw. If it does not, then it
* throws. An error class and a string that should be included in the
* error message can also be asserted.
*/
function assertThrows(fn, ErrorClass, msgIncludes = "", msg) {
let doesThrow = false;
let error = null;
try {
fn();
}
catch (e) {
if (e instanceof Error === false) {
throw new AssertionError("A non-Error object was thrown.");
}
if (ErrorClass && !(e instanceof ErrorClass)) {
msg =
`Expected error to be instance of "${ErrorClass.name}", but was "${e.constructor.name}"${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
if (msgIncludes &&
!(0, colors_js_1.stripColor)(e.message).includes((0, colors_js_1.stripColor)(msgIncludes))) {
msg =
`Expected error message to include "${msgIncludes}", but got "${e.message}"${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
doesThrow = true;
error = e;
}
if (!doesThrow) {
msg = `Expected function to throw${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
return error;
}
exports.assertThrows = assertThrows;
/**
* Executes a function which returns a promise, expecting it to throw or reject.
* If it does not, then it throws. An error class and a string that should be
* included in the error message can also be asserted.
*/
async function assertThrowsAsync(fn, ErrorClass, msgIncludes = "", msg) {
let doesThrow = false;
let error = null;
try {
await fn();
}
catch (e) {
if (e instanceof Error === false) {
throw new AssertionError("A non-Error object was thrown or rejected.");
}
if (ErrorClass && !(e instanceof ErrorClass)) {
msg =
`Expected error to be instance of "${ErrorClass.name}", but got "${e.name}"${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
if (msgIncludes &&
!(0, colors_js_1.stripColor)(e.message).includes((0, colors_js_1.stripColor)(msgIncludes))) {
msg =
`Expected error message to include "${msgIncludes}", but got "${e.message}"${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
doesThrow = true;
error = e;
}
if (!doesThrow) {
msg = `Expected function to throw${msg ? `: ${msg}` : "."}`;
throw new AssertionError(msg);
}
return error;
}
exports.assertThrowsAsync = assertThrowsAsync;
/** Use this to stub out methods that will throw when invoked. */
function unimplemented(msg) {
throw new AssertionError(msg || "unimplemented");
}
exports.unimplemented = unimplemented;
/** Use this to assert unreachable code. */
function unreachable() {
throw new AssertionError("unreachable");
}
exports.unreachable = unreachable;

View File

@@ -0,0 +1,91 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addMatchers = exports.expect = void 0;
const builtInMatchers = __importStar(require("./matchers.js"));
const asserts_js_1 = require("../../std@0.97.0/testing/asserts.js");
const matchers = {
...builtInMatchers,
};
function expect(value) {
let isNot = false;
let isPromised = false;
const self = new Proxy({}, {
get(_, name) {
if (name === "not") {
isNot = !isNot;
return self;
}
if (name === "resolves") {
if (!(value instanceof Promise)) {
throw new asserts_js_1.AssertionError("expected value must be a Promise");
}
isPromised = true;
return self;
}
if (name === "rejects") {
if (!(value instanceof Promise)) {
throw new asserts_js_1.AssertionError("expected value must be a Promise");
}
value = value.then((value) => {
throw new asserts_js_1.AssertionError(`Promise did not reject. resolved to ${value}`);
}, (err) => err);
isPromised = true;
return self;
}
const matcher = matchers[name];
if (!matcher) {
throw new TypeError(typeof name === "string"
? `matcher not found: ${name}`
: "matcher not found");
}
return (...args) => {
function applyMatcher(value, args) {
if (isNot) {
let result = matcher(value, ...args);
if (result.pass) {
throw new asserts_js_1.AssertionError("should not " + result.message);
}
}
else {
let result = matcher(value, ...args);
if (!result.pass) {
throw new asserts_js_1.AssertionError(result.message || "Unknown error");
}
}
}
return isPromised
? value.then((value) => applyMatcher(value, args))
: applyMatcher(value, args);
};
},
});
return self;
}
exports.expect = expect;
function addMatchers(newMatchers) {
Object.assign(matchers, newMatchers);
}
exports.addMatchers = addMatchers;

View File

@@ -0,0 +1,405 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toHaveNthReturnedWith = exports.toHaveReturnedTimes = exports.toHaveLastReturnedWith = exports.toHaveReturned = exports.toHaveReturnedWith = exports.toHaveBeenNthCalledWith = exports.toHaveBeenLastCalledWith = exports.toHaveBeenCalledWith = exports.toHaveBeenCalledTimes = exports.toHaveBeenCalled = exports.toThrow = exports.toContain = exports.toHaveLength = exports.toHaveProperty = exports.toMatch = exports.toBeInstanceOf = exports.toBeNaN = exports.toBeNull = exports.toBeUndefined = exports.toBeDefined = exports.toBeFalsy = exports.toBeTruthy = exports.toBeLessThanOrEqual = exports.toBeGreaterThanOrEqual = exports.toBeLessThan = exports.toBeGreaterThan = exports.toEqual = exports.toBe = void 0;
const dntShim = __importStar(require("../../../../_dnt.test_shims.js"));
const asserts_js_1 = require("../../std@0.97.0/testing/asserts.js");
const _diff_js_1 = require("../../std@0.97.0/testing/_diff.js");
const colors_js_1 = require("../../std@0.97.0/fmt/colors.js");
const mock = __importStar(require("./mock.js"));
const ACTUAL = (0, colors_js_1.red)((0, colors_js_1.bold)('actual'));
const EXPECTED = (0, colors_js_1.green)((0, colors_js_1.bold)('expected'));
const CAN_NOT_DISPLAY = '[Cannot display]';
function createStr(v) {
try {
return dntShim.Deno.inspect(v);
}
catch (e) {
return (0, colors_js_1.red)(CAN_NOT_DISPLAY);
}
}
function createColor(diffType) {
switch (diffType) {
case _diff_js_1.DiffType.added:
return (s) => (0, colors_js_1.green)((0, colors_js_1.bold)(s));
case _diff_js_1.DiffType.removed:
return (s) => (0, colors_js_1.red)((0, colors_js_1.bold)(s));
default:
return colors_js_1.white;
}
}
function createSign(diffType) {
switch (diffType) {
case _diff_js_1.DiffType.added:
return '+ ';
case _diff_js_1.DiffType.removed:
return '- ';
default:
return ' ';
}
}
function buildMessage(diffResult) {
return diffResult
.map((result) => {
const c = createColor(result.type);
return c(`${createSign(result.type)}${result.value}`);
})
.join('\n');
}
function buildDiffMessage(actual, expected) {
const actualString = createStr(actual);
const expectedString = createStr(expected);
let message;
try {
const diffResult = (0, _diff_js_1.diff)(actualString.split('\n'), expectedString.split('\n'));
return buildMessage(diffResult);
}
catch (e) {
return `\n${(0, colors_js_1.red)(CAN_NOT_DISPLAY)} + \n\n`;
}
}
function buildFail(message) {
return {
pass: false,
message
};
}
function toBe(actual, expected) {
if (actual === expected)
return { pass: true };
return buildFail(`expect(${ACTUAL}).toBe(${EXPECTED})\n\n${buildDiffMessage(actual, expected)}`);
}
exports.toBe = toBe;
function toEqual(actual, expected) {
if ((0, asserts_js_1.equal)(actual, expected))
return { pass: true };
return buildFail(`expect(${ACTUAL}).toEqual(${EXPECTED})\n\n${buildDiffMessage(actual, expected)}`);
}
exports.toEqual = toEqual;
function toBeGreaterThan(actual, comparison) {
if (actual > comparison)
return { pass: true };
const actualString = createStr(actual);
const comparisonString = createStr(comparison);
return buildFail(`expect(${ACTUAL}).toBeGreaterThan(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} is not greater than ${(0, colors_js_1.green)(comparisonString)}`);
}
exports.toBeGreaterThan = toBeGreaterThan;
function toBeLessThan(actual, comparison) {
if (actual < comparison)
return { pass: true };
const actualString = createStr(actual);
const comparisonString = createStr(comparison);
return buildFail(`expect(${ACTUAL}).toBeLessThan(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} is not less than ${(0, colors_js_1.green)(comparisonString)}`);
}
exports.toBeLessThan = toBeLessThan;
function toBeGreaterThanOrEqual(actual, comparison) {
if (actual >= comparison)
return { pass: true };
const actualString = createStr(actual);
const comparisonString = createStr(comparison);
return buildFail(`expect(${ACTUAL}).toBeGreaterThanOrEqual(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} is not greater than or equal to ${(0, colors_js_1.green)(comparisonString)}`);
}
exports.toBeGreaterThanOrEqual = toBeGreaterThanOrEqual;
function toBeLessThanOrEqual(actual, comparison) {
if (actual <= comparison)
return { pass: true };
const actualString = createStr(actual);
const comparisonString = createStr(comparison);
return buildFail(`expect(${ACTUAL}).toBeLessThanOrEqual(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} is not less than or equal to ${(0, colors_js_1.green)(comparisonString)}`);
}
exports.toBeLessThanOrEqual = toBeLessThanOrEqual;
function toBeTruthy(value) {
if (value)
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeTruthy()
${(0, colors_js_1.red)(actualString)} is not truthy`);
}
exports.toBeTruthy = toBeTruthy;
function toBeFalsy(value) {
if (!value)
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeFalsy()\n\n ${(0, colors_js_1.red)(actualString)} is not falsy`);
}
exports.toBeFalsy = toBeFalsy;
function toBeDefined(value) {
if (typeof value !== 'undefined')
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeDefined()\n\n ${(0, colors_js_1.red)(actualString)} is not defined`);
}
exports.toBeDefined = toBeDefined;
function toBeUndefined(value) {
if (typeof value === 'undefined')
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeUndefined()\n\n ${(0, colors_js_1.red)(actualString)} is defined but should be undefined`);
}
exports.toBeUndefined = toBeUndefined;
function toBeNull(value) {
if (value === null)
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeNull()\n\n ${(0, colors_js_1.red)(actualString)} should be null`);
}
exports.toBeNull = toBeNull;
function toBeNaN(value) {
if (typeof value === 'number' && isNaN(value))
return { pass: true };
const actualString = createStr(value);
return buildFail(`expect(${ACTUAL}).toBeNaN()\n\n ${(0, colors_js_1.red)(actualString)} should be NaN`);
}
exports.toBeNaN = toBeNaN;
function toBeInstanceOf(value, expected) {
if (value instanceof expected)
return { pass: true };
const actualString = createStr(value);
const expectedString = createStr(expected);
return buildFail(`expect(${ACTUAL}).toBeInstanceOf(${EXPECTED})\n\n expected ${(0, colors_js_1.green)(expected.name)} but received ${(0, colors_js_1.red)(actualString)}`);
}
exports.toBeInstanceOf = toBeInstanceOf;
function toMatch(value, pattern) {
const valueStr = value.toString();
if (typeof pattern === 'string') {
if (valueStr.indexOf(pattern) !== -1)
return { pass: true };
const actualString = createStr(value);
const patternString = createStr(pattern);
return buildFail(`expect(${ACTUAL}).toMatch(${EXPECTED})\n\n expected ${(0, colors_js_1.red)(actualString)} to contain ${(0, colors_js_1.green)(patternString)}`);
}
else if (pattern instanceof RegExp) {
if (pattern.exec(valueStr))
return { pass: true };
const actualString = createStr(value);
const patternString = createStr(pattern);
return buildFail(`expect(${ACTUAL}).toMatch(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} did not match regex ${(0, colors_js_1.green)(patternString)}`);
}
else {
return buildFail('Invalid internal state');
}
}
exports.toMatch = toMatch;
function toHaveProperty(value, propName) {
if (typeof value === 'object' && typeof value[propName] !== 'undefined') {
return { pass: true };
}
const actualString = createStr(value);
const propNameString = createStr(propName);
return buildFail(`expect(${ACTUAL}).toHaveProperty(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} did not contain property ${(0, colors_js_1.green)(propNameString)}`);
}
exports.toHaveProperty = toHaveProperty;
function toHaveLength(value, length) {
if (value?.length === length)
return { pass: true };
const actualString = createStr(value.length);
const lengthString = createStr(length);
return buildFail(`expect(${ACTUAL}).toHaveLength(${EXPECTED})\n\n expected array to have length ${(0, colors_js_1.green)(lengthString)} but was ${(0, colors_js_1.red)(actualString)}`);
}
exports.toHaveLength = toHaveLength;
function toContain(value, item) {
if (value && typeof value.includes === 'function' && value.includes(item)) {
return { pass: true };
}
const actualString = createStr(value);
const itemString = createStr(item);
if (value && typeof value.includes === 'function') {
return buildFail(`expect(${ACTUAL}).toContain(${EXPECTED})\n\n ${(0, colors_js_1.red)(actualString)} did not contain ${(0, colors_js_1.green)(itemString)}`);
}
else {
return buildFail(`expect(${ACTUAL}).toContain(${EXPECTED})\n\n expected ${(0, colors_js_1.red)(actualString)} to have an includes method but it is ${(0, colors_js_1.green)(itemString)}`);
}
}
exports.toContain = toContain;
function toThrow(value, error) {
let fn;
if (typeof value === 'function') {
fn = value;
try {
value = value();
}
catch (err) {
value = err;
}
}
const actualString = createStr(fn);
const errorString = createStr(error);
if (value instanceof Error) {
if (typeof error === 'string') {
if (!value.message.includes(error)) {
return buildFail(`expect(${ACTUAL}).toThrow(${EXPECTED})\n\nexpected ${(0, colors_js_1.red)(actualString)} to throw error matching ${(0, colors_js_1.green)(errorString)} but it threw ${(0, colors_js_1.red)(value.toString())}`);
}
}
else if (error instanceof RegExp) {
if (!value.message.match(error)) {
return buildFail(`expect(${ACTUAL}).toThrow(${EXPECTED})\n\nexpected ${(0, colors_js_1.red)(actualString)} to throw error matching ${(0, colors_js_1.green)(errorString)} but it threw ${(0, colors_js_1.red)(value.toString())}`);
}
}
return { pass: true };
}
else {
return buildFail(`expect(${ACTUAL}).toThrow(${EXPECTED})\n\nexpected ${(0, colors_js_1.red)(actualString)} to throw but it did not`);
}
}
exports.toThrow = toThrow;
function extractMockCalls(value, name) {
if (typeof value !== 'function') {
return {
calls: null,
error: `${name} only works on mock functions. received: ${value}`
};
}
const calls = mock.calls(value);
if (calls === null) {
return { calls: null, error: `${name} only works on mock functions` };
}
return { calls };
}
function toHaveBeenCalled(value) {
const { calls, error } = extractMockCalls(value, 'toHaveBeenCalled');
if (error)
return buildFail(error);
const actualString = createStr(value);
if (calls && calls.length !== 0)
return { pass: true };
return buildFail(`expect(${ACTUAL}).toHaveBeenCalled()\n\n ${(0, colors_js_1.red)(actualString)} was not called`);
}
exports.toHaveBeenCalled = toHaveBeenCalled;
function toHaveBeenCalledTimes(value, times) {
const { calls, error } = extractMockCalls(value, 'toHaveBeenCalledTimes');
if (error)
return buildFail(error);
if (!calls)
return buildFail('Invalid internal state');
if (calls && calls.length === times)
return { pass: true };
return buildFail(`expect(${ACTUAL}).toHaveBeenCalledTimes(${EXPECTED})\n\n expected ${times} calls but was called: ${calls.length}`);
}
exports.toHaveBeenCalledTimes = toHaveBeenCalledTimes;
function toHaveBeenCalledWith(value, ...args) {
const { calls, error } = extractMockCalls(value, 'toHaveBeenCalledWith');
if (error)
return buildFail(error);
const wasCalledWith = calls && calls.some((c) => (0, asserts_js_1.equal)(c.args, args));
if (wasCalledWith)
return { pass: true };
const argsString = createStr(args);
return buildFail(`expect(${ACTUAL}).toHaveBeenCalledWith(${EXPECTED})\n\n function was not called with: ${(0, colors_js_1.green)(argsString)}`);
}
exports.toHaveBeenCalledWith = toHaveBeenCalledWith;
function toHaveBeenLastCalledWith(value, ...args) {
const { calls, error } = extractMockCalls(value, 'toHaveBeenLastCalledWith');
if (error)
return buildFail(error);
if (!calls || !calls.length) {
return buildFail(`expect(${ACTUAL}).toHaveBeenLastCalledWith(...${EXPECTED})\n\n expect last call args to be ${args} but was not called`);
}
const lastCall = calls[calls.length - 1];
if ((0, asserts_js_1.equal)(lastCall.args, args))
return { pass: true };
return buildFail(`expect(${ACTUAL}).toHaveBeenLastCalledWith(...${EXPECTED})\n\n expect last call args to be ${args} but was: ${lastCall.args}`);
}
exports.toHaveBeenLastCalledWith = toHaveBeenLastCalledWith;
function toHaveBeenNthCalledWith(value, nth, ...args) {
const { calls, error } = extractMockCalls(value, 'toHaveBeenNthCalledWith');
if (error)
return buildFail(error);
const nthCall = calls && calls[nth - 1];
if (nthCall) {
if ((0, asserts_js_1.equal)(nthCall.args, args))
return { pass: true };
return buildFail(`expect(${ACTUAL}).toHaveBeenNthCalledWith(${EXPECTED})\n\n expect ${nth}th call args to be ${args} but was: ${nthCall.args}`);
}
else {
return buildFail(`expect(${ACTUAL}).toHaveBeenNthCalledWith(${EXPECTED})\n\n ${nth}th call was not made.`);
}
}
exports.toHaveBeenNthCalledWith = toHaveBeenNthCalledWith;
function toHaveReturnedWith(value, result) {
const { calls, error } = extractMockCalls(value, 'toHaveReturnedWith');
if (error)
return buildFail(error);
const wasReturnedWith = calls && calls.some((c) => c.returns && (0, asserts_js_1.equal)(c.returned, result));
if (wasReturnedWith)
return { pass: true };
return buildFail(`expect(${ACTUAL}).toHaveReturnedWith(${EXPECTED})\n\n function did not return: ${result}`);
}
exports.toHaveReturnedWith = toHaveReturnedWith;
function toHaveReturned(value) {
const { calls, error } = extractMockCalls(value, 'toHaveReturned');
if (error)
return buildFail(error);
if (calls && calls.some((c) => c.returns))
return { pass: true };
// TODO(allain): better messages
return buildFail(`expected function to return but it never did`);
}
exports.toHaveReturned = toHaveReturned;
// TODO(allain): better messages
function toHaveLastReturnedWith(value, expected) {
const { calls, error } = extractMockCalls(value, 'toHaveLastReturnedWith');
if (error)
return buildFail(error);
const lastCall = calls && calls[calls.length - 1];
if (!lastCall) {
return buildFail('no calls made to function');
}
if (lastCall.throws) {
return buildFail(`last call to function threw: ${lastCall.thrown}`);
}
if ((0, asserts_js_1.equal)(lastCall.returned, expected))
return { pass: true };
return buildFail(`expected last call to return ${expected} but returned: ${lastCall.returned}`);
}
exports.toHaveLastReturnedWith = toHaveLastReturnedWith;
function toHaveReturnedTimes(value, times) {
const { calls, error } = extractMockCalls(value, 'toHaveReturnedTimes');
if (error)
return buildFail(error);
const returnCount = calls && calls.filter((c) => c.returns).length;
if (returnCount !== times) {
return buildFail(`expected ${times} returned times but returned ${returnCount} times`);
}
return { pass: true };
}
exports.toHaveReturnedTimes = toHaveReturnedTimes;
function toHaveNthReturnedWith(value, nth, expected) {
const { calls, error } = extractMockCalls(value, 'toHaveNthReturnedWith');
if (error)
return buildFail(error);
const nthCall = calls && calls[nth - 1];
if (!nthCall) {
return buildFail(`${nth} calls were now made`);
}
if (nthCall.throws) {
return buildFail(`${nth}th call to function threw: ${nthCall.thrown}`);
}
if (!(0, asserts_js_1.equal)(nthCall.returned, expected)) {
return buildFail(`expected ${nth}th call to return ${expected} but returned: ${nthCall.returned}`);
}
return { pass: true };
}
exports.toHaveNthReturnedWith = toHaveNthReturnedWith;

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.calls = exports.fn = void 0;
const MOCK_SYMBOL = Symbol.for("@MOCK");
function fn(...stubs) {
const calls = [];
const f = (...args) => {
const stub = stubs.length === 1
? // keep reusing the first
stubs[0]
: // pick the exact mock for the current call
stubs[calls.length];
try {
const returned = stub ? stub(...args) : undefined;
calls.push({
args,
returned,
timestamp: Date.now(),
returns: true,
throws: false,
});
return returned;
}
catch (err) {
calls.push({
args,
timestamp: Date.now(),
returns: false,
thrown: err,
throws: true,
});
throw err;
}
};
Object.defineProperty(f, MOCK_SYMBOL, {
value: { calls },
writable: false,
});
return f;
}
exports.fn = fn;
function calls(f) {
const mockInfo = f[MOCK_SYMBOL];
if (!mockInfo)
throw new Error("callCount only available on mock functions");
return [...mockInfo.calls];
}
exports.calls = calls;

View File

@@ -0,0 +1,40 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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.it = exports.mock = void 0;
const dntShim = __importStar(require("../../../../_dnt.test_shims.js"));
const m = __importStar(require("./mock.js"));
exports.mock = m;
__exportStar(require("./expect.js"), exports);
function it(name, fn) {
dntShim.Deno.test({
name,
fn,
});
}
exports.it = it;

View File

@@ -0,0 +1,57 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MappedAParser = exports.ConcatParsers = exports.LiteralsParser = exports.ArrayOfParser = exports.NamedParser = exports.saferStringify = exports.StringParser = exports.ShapeParser = exports.OrParsers = exports.ObjectParser = exports.NumberParser = exports.NilParser = exports.GuardParser = exports.FunctionParser = exports.BoolParser = exports.ArrayParser = exports.AnyParser = void 0;
__exportStar(require("./src/matches.js"), exports);
const matches_js_1 = __importDefault(require("./src/matches.js"));
var any_parser_js_1 = require("./src/parsers/any-parser.js");
Object.defineProperty(exports, "AnyParser", { enumerable: true, get: function () { return any_parser_js_1.AnyParser; } });
var array_parser_js_1 = require("./src/parsers/array-parser.js");
Object.defineProperty(exports, "ArrayParser", { enumerable: true, get: function () { return array_parser_js_1.ArrayParser; } });
var bool_parser_js_1 = require("./src/parsers/bool-parser.js");
Object.defineProperty(exports, "BoolParser", { enumerable: true, get: function () { return bool_parser_js_1.BoolParser; } });
var function_parser_js_1 = require("./src/parsers/function-parser.js");
Object.defineProperty(exports, "FunctionParser", { enumerable: true, get: function () { return function_parser_js_1.FunctionParser; } });
var guard_parser_js_1 = require("./src/parsers/guard-parser.js");
Object.defineProperty(exports, "GuardParser", { enumerable: true, get: function () { return guard_parser_js_1.GuardParser; } });
var nill_parser_js_1 = require("./src/parsers/nill-parser.js");
Object.defineProperty(exports, "NilParser", { enumerable: true, get: function () { return nill_parser_js_1.NilParser; } });
var number_parser_js_1 = require("./src/parsers/number-parser.js");
Object.defineProperty(exports, "NumberParser", { enumerable: true, get: function () { return number_parser_js_1.NumberParser; } });
var object_parser_js_1 = require("./src/parsers/object-parser.js");
Object.defineProperty(exports, "ObjectParser", { enumerable: true, get: function () { return object_parser_js_1.ObjectParser; } });
var or_parser_js_1 = require("./src/parsers/or-parser.js");
Object.defineProperty(exports, "OrParsers", { enumerable: true, get: function () { return or_parser_js_1.OrParsers; } });
var shape_parser_js_1 = require("./src/parsers/shape-parser.js");
Object.defineProperty(exports, "ShapeParser", { enumerable: true, get: function () { return shape_parser_js_1.ShapeParser; } });
var string_parser_js_1 = require("./src/parsers/string-parser.js");
Object.defineProperty(exports, "StringParser", { enumerable: true, get: function () { return string_parser_js_1.StringParser; } });
var utils_js_1 = require("./src/utils.js");
Object.defineProperty(exports, "saferStringify", { enumerable: true, get: function () { return utils_js_1.saferStringify; } });
var named_js_1 = require("./src/parsers/named.js");
Object.defineProperty(exports, "NamedParser", { enumerable: true, get: function () { return named_js_1.NamedParser; } });
var array_of_parser_js_1 = require("./src/parsers/array-of-parser.js");
Object.defineProperty(exports, "ArrayOfParser", { enumerable: true, get: function () { return array_of_parser_js_1.ArrayOfParser; } });
var literal_parser_js_1 = require("./src/parsers/literal-parser.js");
Object.defineProperty(exports, "LiteralsParser", { enumerable: true, get: function () { return literal_parser_js_1.LiteralsParser; } });
var concat_parser_js_1 = require("./src/parsers/concat-parser.js");
Object.defineProperty(exports, "ConcatParsers", { enumerable: true, get: function () { return concat_parser_js_1.ConcatParsers; } });
var mapped_parser_js_1 = require("./src/parsers/mapped-parser.js");
Object.defineProperty(exports, "MappedAParser", { enumerable: true, get: function () { return mapped_parser_js_1.MappedAParser; } });
exports.default = matches_js_1.default;

View File

@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unknown = exports.tuple = exports.string = exports.some = exports.shape = exports.regex = exports.recursive = exports.partial = exports.parserName = exports.Parser = exports.Parse = exports.oneOf = exports.object = exports.number = exports.nill = exports.natural = exports.literals = exports.literal = exports.isFunction = exports.instanceOf = exports.guard = exports.every = exports.dictionary = exports.deferred = exports.boolean = exports.arrayOf = exports.array = exports.anyOf = exports.any = exports.allOf = exports.matches = exports.Validator = void 0;
const index_js_1 = require("./parsers/index.js");
Object.defineProperty(exports, "any", { enumerable: true, get: function () { return index_js_1.any; } });
Object.defineProperty(exports, "arrayOf", { enumerable: true, get: function () { return index_js_1.arrayOf; } });
Object.defineProperty(exports, "boolean", { enumerable: true, get: function () { return index_js_1.boolean; } });
Object.defineProperty(exports, "deferred", { enumerable: true, get: function () { return index_js_1.deferred; } });
Object.defineProperty(exports, "dictionary", { enumerable: true, get: function () { return index_js_1.dictionary; } });
Object.defineProperty(exports, "every", { enumerable: true, get: function () { return index_js_1.every; } });
Object.defineProperty(exports, "guard", { enumerable: true, get: function () { return index_js_1.guard; } });
Object.defineProperty(exports, "instanceOf", { enumerable: true, get: function () { return index_js_1.instanceOf; } });
Object.defineProperty(exports, "isFunction", { enumerable: true, get: function () { return index_js_1.isFunction; } });
Object.defineProperty(exports, "literal", { enumerable: true, get: function () { return index_js_1.literal; } });
Object.defineProperty(exports, "literals", { enumerable: true, get: function () { return index_js_1.literals; } });
Object.defineProperty(exports, "natural", { enumerable: true, get: function () { return index_js_1.natural; } });
Object.defineProperty(exports, "number", { enumerable: true, get: function () { return index_js_1.number; } });
Object.defineProperty(exports, "object", { enumerable: true, get: function () { return index_js_1.object; } });
Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return index_js_1.Parser; } });
Object.defineProperty(exports, "Parser", { enumerable: true, get: function () { return index_js_1.Parser; } });
Object.defineProperty(exports, "partial", { enumerable: true, get: function () { return index_js_1.partial; } });
Object.defineProperty(exports, "recursive", { enumerable: true, get: function () { return index_js_1.recursive; } });
Object.defineProperty(exports, "regex", { enumerable: true, get: function () { return index_js_1.regex; } });
Object.defineProperty(exports, "shape", { enumerable: true, get: function () { return index_js_1.shape; } });
Object.defineProperty(exports, "some", { enumerable: true, get: function () { return index_js_1.some; } });
Object.defineProperty(exports, "string", { enumerable: true, get: function () { return index_js_1.string; } });
Object.defineProperty(exports, "tuple", { enumerable: true, get: function () { return index_js_1.tuple; } });
const named_js_1 = require("./parsers/named.js");
Object.defineProperty(exports, "parserName", { enumerable: true, get: function () { return named_js_1.parserName; } });
const simple_parsers_js_1 = require("./parsers/simple-parsers.js");
Object.defineProperty(exports, "unknown", { enumerable: true, get: function () { return simple_parsers_js_1.unknown; } });
class Matched {
constructor(value) {
Object.defineProperty(this, "value", {
enumerable: true,
configurable: true,
writable: true,
value: value
});
Object.defineProperty(this, "when", {
enumerable: true,
configurable: true,
writable: true,
value: ((..._args) => {
// deno-lint-ignore no-explicit-any
return this;
// deno-lint-ignore no-explicit-any
})
});
Object.defineProperty(this, "unwrap", {
enumerable: true,
configurable: true,
writable: true,
value: (() => {
return this.value;
// deno-lint-ignore no-explicit-any
})
});
}
defaultTo(_defaultValue) {
return this.value;
}
defaultToLazy(_getValue) {
return this.value;
}
}
class MatchMore {
constructor(a) {
Object.defineProperty(this, "a", {
enumerable: true,
configurable: true,
writable: true,
value: a
});
Object.defineProperty(this, "when", {
enumerable: true,
configurable: true,
writable: true,
value: ((...args) => {
const [outcome, ...matchers] = args.reverse();
// deno-lint-ignore no-this-alias
const me = this;
const parser = exports.matches.some(...matchers.map((matcher) =>
// deno-lint-ignore no-explicit-any
matcher instanceof index_js_1.Parser ? matcher : (0, index_js_1.literal)(matcher)));
const result = parser.enumParsed(this.a);
if ("error" in result) {
// deno-lint-ignore no-explicit-any
return me;
}
const { value } = result;
if (outcome instanceof Function) {
// deno-lint-ignore no-explicit-any
return new Matched(outcome(value));
}
// deno-lint-ignore no-explicit-any
return new Matched(outcome);
// deno-lint-ignore no-explicit-any
})
});
Object.defineProperty(this, "unwrap", {
enumerable: true,
configurable: true,
writable: true,
value: (() => {
throw new Error("Expecting that value is matched");
// deno-lint-ignore no-explicit-any
})
});
}
defaultTo(value) {
return value;
}
defaultToLazy(getValue) {
return getValue();
}
}
/**
* Want to be able to bring in the declarative nature that a functional programming
* language feature of the pattern matching and the switch statement. With the destructors
* the only thing left was to find the correct structure then move move forward.
* Using a structure in chainable fashion allows for a syntax that works with typescript
* while looking similar to matches statements in other languages
*
* Use: matches('a value').when(matches.isNumber, (aNumber) => aNumber + 4).defaultTo('fallback value')
*/
exports.matches = Object.assign(function matchesFn(value) {
return new MatchMore(value);
}, {
array: index_js_1.isArray,
arrayOf: index_js_1.arrayOf,
some: index_js_1.some,
tuple: index_js_1.tuple,
regex: index_js_1.regex,
number: index_js_1.number,
natural: index_js_1.natural,
isFunction: index_js_1.isFunction,
object: index_js_1.object,
string: index_js_1.string,
shape: index_js_1.shape,
partial: index_js_1.partial,
literal: index_js_1.literal,
every: index_js_1.every,
guard: index_js_1.guard,
unknown: simple_parsers_js_1.unknown,
any: index_js_1.any,
boolean: index_js_1.boolean,
dictionary: index_js_1.dictionary,
literals: index_js_1.literals,
nill: index_js_1.isNill,
instanceOf: index_js_1.instanceOf,
Parse: index_js_1.Parser,
parserName: named_js_1.parserName,
recursive: index_js_1.recursive,
deferred: index_js_1.deferred,
});
const array = index_js_1.isArray;
exports.array = array;
const nill = index_js_1.isNill;
exports.nill = nill;
const Parse = index_js_1.Parser;
exports.Parse = Parse;
const oneOf = index_js_1.some;
exports.oneOf = oneOf;
const anyOf = index_js_1.some;
exports.anyOf = anyOf;
const allOf = index_js_1.every;
exports.allOf = allOf;
exports.default = exports.matches;

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnyParser = void 0;
class AnyParser {
constructor(description = {
name: "Any",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
return onParse.parsed(a);
}
}
exports.AnyParser = AnyParser;

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayOf = exports.ArrayOfParser = void 0;
// deno-lint-ignore-file no-explicit-any
const index_js_1 = require("./index.js");
/**
* Given an object, we want to make sure the key exists and that the value on
* the key matches the parser
* Note: This will mutate the value sent through
*/
class ArrayOfParser {
constructor(parser, description = {
name: "ArrayOf",
children: [parser],
extras: [],
}) {
Object.defineProperty(this, "parser", {
enumerable: true,
configurable: true,
writable: true,
value: parser
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (!Array.isArray(a)) {
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
const values = [...a];
for (let index = 0; index < values.length; index++) {
const result = this.parser.enumParsed(values[index]);
if ("error" in result) {
result.error.keys.push("" + index);
return onParse.invalid(result.error);
}
else {
values[index] = result.value;
}
}
return onParse.parsed(values);
}
}
exports.ArrayOfParser = ArrayOfParser;
/**
* We would like to validate that all of the array is of the same type
* @param validator What is the validator for the values in the array
*/
function arrayOf(validator) {
return new index_js_1.Parser(new ArrayOfParser(validator));
}
exports.arrayOf = arrayOf;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayParser = void 0;
class ArrayParser {
constructor(description = {
name: "Array",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (Array.isArray(a))
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.ArrayParser = ArrayParser;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BoolParser = void 0;
class BoolParser {
constructor(description = {
name: "Boolean",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (a === true || a === false)
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.BoolParser = BoolParser;

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConcatParsers = void 0;
class ConcatParsers {
constructor(parent, otherParser, description = {
name: "Concat",
children: [parent, otherParser],
extras: [],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "otherParser", {
enumerable: true,
configurable: true,
writable: true,
value: otherParser
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
static of(parent, otherParser) {
if (parent.unwrappedParser().description.name === "Any") {
return otherParser;
}
if (otherParser.unwrappedParser().description.name === "Any") {
return parent;
}
return new ConcatParsers(parent, otherParser);
}
parse(a, onParse) {
const parent = this.parent.enumParsed(a);
if ("error" in parent) {
return onParse.invalid(parent.error);
}
const other = this.otherParser.enumParsed(parent.value);
if ("error" in other) {
return onParse.invalid(other.error);
}
return onParse.parsed(other.value);
}
}
exports.ConcatParsers = ConcatParsers;

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultParser = void 0;
class DefaultParser {
constructor(parent, defaultValue, description = {
name: "Default",
children: [parent],
extras: [defaultValue],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "defaultValue", {
enumerable: true,
configurable: true,
writable: true,
value: defaultValue
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
// deno-lint-ignore no-this-alias
const parser = this;
const defaultValue = this.defaultValue;
if (a == null) {
return onParse.parsed(defaultValue);
}
const parentCheck = this.parent.enumParsed(a);
if ("error" in parentCheck) {
parentCheck.error.parser = parser;
return onParse.invalid(parentCheck.error);
}
return onParse.parsed(parentCheck.value);
}
}
exports.DefaultParser = DefaultParser;

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deferred = exports.DeferredParser = void 0;
const parser_js_1 = require("./parser.js");
/**
* This is needed when the typescript has a recursive, mutual types
* type Things = string | [OtherThings]
* type OtherThings = {type: 'other', value:Things }
*/
class DeferredParser {
static create() {
return new DeferredParser();
}
constructor(description = {
name: "Deferred",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
Object.defineProperty(this, "parser", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
setParser(parser) {
this.parser = new parser_js_1.Parser(parser);
return this;
}
parse(a, onParse) {
if (!this.parser) {
return onParse.invalid({
value: "Not Set Up",
keys: [],
parser: this,
});
}
return this.parser.parse(a, onParse);
}
}
exports.DeferredParser = DeferredParser;
/**
* Must pass the shape that we expect since typescript as of this point
* can't infer with recursive like structures like this.
* @returns [Parser, setParser] Use the setParser to set the parser later
*/
function deferred() {
const deferred = DeferredParser.create();
function setParser(parser) {
deferred.setParser(parser);
}
return [new parser_js_1.Parser(deferred), setParser];
}
exports.deferred = deferred;

View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dictionary = exports.DictionaryParser = void 0;
// deno-lint-ignore-file no-explicit-any ban-types
const index_js_1 = require("./index.js");
class DictionaryParser {
constructor(parsers, description = {
name: "Dictionary",
children: parsers.reduce((acc, [k, v]) => {
acc.push(k, v);
return acc;
}, []),
extras: [],
}) {
Object.defineProperty(this, "parsers", {
enumerable: true,
configurable: true,
writable: true,
value: parsers
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
const { parsers } = this;
// deno-lint-ignore no-this-alias
const parser = this;
const entries = Object.entries(a);
for (const entry of entries) {
const [key, value] = entry;
const found = findOrError(parsers, key, value, parser);
if (found == undefined)
return onParse.parsed(a);
if ("error" in found)
return onParse.invalid(found.error);
entry[0] = found[0].value;
entry[1] = found[1].value;
}
const answer = Object.fromEntries(entries);
return onParse.parsed(answer);
}
}
exports.DictionaryParser = DictionaryParser;
const dictionary = (...parsers) => {
return index_js_1.object.concat(new DictionaryParser([...parsers]));
};
exports.dictionary = dictionary;
function findOrError(parsers, key, value, parser) {
let foundError;
for (const [keyParser, valueParser] of parsers) {
const enumState = keyParser.enumParsed(key);
const valueState = valueParser.enumParsed(value);
if ("error" in enumState) {
if (!foundError) {
const { error } = enumState;
error.parser = parser;
error.keys.push("" + key);
foundError = { error };
}
continue;
}
const newKey = enumState.value;
if ("error" in valueState) {
if (!foundError) {
const { error } = valueState;
error.keys.push("" + newKey);
foundError = { error };
}
continue;
}
return [enumState, valueState];
}
return foundError;
}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.every = void 0;
// deno-lint-ignore-file no-explicit-any
const index_js_1 = require("./index.js");
/**
* Intersection is a good tool to make sure that the validated value
* is in the intersection of all the validators passed in. Basically an `and`
* operator for validators
*/
function every(...parsers) {
const filteredParsers = parsers.filter((x) => x !== index_js_1.any);
if (filteredParsers.length <= 0) {
return index_js_1.any;
}
const first = filteredParsers.splice(0, 1)[0];
return filteredParsers.reduce((left, right) => {
return left.concat(right);
}, first);
}
exports.every = every;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FunctionParser = void 0;
const utils_js_1 = require("./utils.js");
class FunctionParser {
constructor(description = {
name: "Function",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if ((0, utils_js_1.isFunctionTest)(a))
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.FunctionParser = FunctionParser;

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GuardParser = void 0;
class GuardParser {
constructor(checkIsA, typeName, description = {
name: "Guard",
children: [],
extras: [typeName],
}) {
Object.defineProperty(this, "checkIsA", {
enumerable: true,
configurable: true,
writable: true,
value: checkIsA
});
Object.defineProperty(this, "typeName", {
enumerable: true,
configurable: true,
writable: true,
value: typeName
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (this.checkIsA(a)) {
return onParse.parsed(a);
}
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.GuardParser = GuardParser;

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tuple = exports.string = exports.some = exports.shape = exports.regex = exports.recursive = exports.partial = exports.Parser = exports.object = exports.number = exports.natural = exports.literals = exports.literal = exports.isNumber = exports.isNill = exports.isFunction = exports.isArray = exports.instanceOf = exports.IsAParser = exports.guard = exports.every = exports.dictionary = exports.deferred = exports.boolean = exports.arrayOf = exports.any = void 0;
const utils_js_1 = require("./utils.js");
Object.defineProperty(exports, "isNumber", { enumerable: true, get: function () { return utils_js_1.isNumber; } });
const guard_parser_js_1 = require("./guard-parser.js");
Object.defineProperty(exports, "IsAParser", { enumerable: true, get: function () { return guard_parser_js_1.GuardParser; } });
const parser_js_1 = require("./parser.js");
Object.defineProperty(exports, "Parser", { enumerable: true, get: function () { return parser_js_1.Parser; } });
const simple_parsers_js_1 = require("./simple-parsers.js");
Object.defineProperty(exports, "any", { enumerable: true, get: function () { return simple_parsers_js_1.any; } });
Object.defineProperty(exports, "boolean", { enumerable: true, get: function () { return simple_parsers_js_1.boolean; } });
Object.defineProperty(exports, "guard", { enumerable: true, get: function () { return simple_parsers_js_1.guard; } });
Object.defineProperty(exports, "instanceOf", { enumerable: true, get: function () { return simple_parsers_js_1.instanceOf; } });
Object.defineProperty(exports, "isArray", { enumerable: true, get: function () { return simple_parsers_js_1.isArray; } });
Object.defineProperty(exports, "isFunction", { enumerable: true, get: function () { return simple_parsers_js_1.isFunction; } });
Object.defineProperty(exports, "isNill", { enumerable: true, get: function () { return simple_parsers_js_1.isNill; } });
Object.defineProperty(exports, "natural", { enumerable: true, get: function () { return simple_parsers_js_1.natural; } });
Object.defineProperty(exports, "number", { enumerable: true, get: function () { return simple_parsers_js_1.number; } });
Object.defineProperty(exports, "object", { enumerable: true, get: function () { return simple_parsers_js_1.object; } });
Object.defineProperty(exports, "regex", { enumerable: true, get: function () { return simple_parsers_js_1.regex; } });
Object.defineProperty(exports, "string", { enumerable: true, get: function () { return simple_parsers_js_1.string; } });
const some_parser_js_1 = require("./some-parser.js");
Object.defineProperty(exports, "some", { enumerable: true, get: function () { return some_parser_js_1.some; } });
const every_parser_js_1 = require("./every-parser.js");
Object.defineProperty(exports, "every", { enumerable: true, get: function () { return every_parser_js_1.every; } });
const dictionary_parser_js_1 = require("./dictionary-parser.js");
Object.defineProperty(exports, "dictionary", { enumerable: true, get: function () { return dictionary_parser_js_1.dictionary; } });
const shape_parser_js_1 = require("./shape-parser.js");
Object.defineProperty(exports, "partial", { enumerable: true, get: function () { return shape_parser_js_1.partial; } });
Object.defineProperty(exports, "shape", { enumerable: true, get: function () { return shape_parser_js_1.shape; } });
const tuple_parser_js_1 = require("./tuple-parser.js");
Object.defineProperty(exports, "tuple", { enumerable: true, get: function () { return tuple_parser_js_1.tuple; } });
const array_of_parser_js_1 = require("./array-of-parser.js");
Object.defineProperty(exports, "arrayOf", { enumerable: true, get: function () { return array_of_parser_js_1.arrayOf; } });
const literal_parser_js_1 = require("./literal-parser.js");
Object.defineProperty(exports, "literal", { enumerable: true, get: function () { return literal_parser_js_1.literal; } });
Object.defineProperty(exports, "literals", { enumerable: true, get: function () { return literal_parser_js_1.literals; } });
const recursive_parser_js_1 = require("./recursive-parser.js");
Object.defineProperty(exports, "recursive", { enumerable: true, get: function () { return recursive_parser_js_1.recursive; } });
const deferred_parser_js_1 = require("./deferred-parser.js");
Object.defineProperty(exports, "deferred", { enumerable: true, get: function () { return deferred_parser_js_1.deferred; } });

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.literals = exports.literal = exports.LiteralsParser = void 0;
const parser_js_1 = require("./parser.js");
class LiteralsParser {
constructor(values, description = {
name: "Literal",
children: [],
extras: values,
}) {
Object.defineProperty(this, "values", {
enumerable: true,
configurable: true,
writable: true,
value: values
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (this.values.indexOf(a) >= 0) {
return onParse.parsed(a);
}
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.LiteralsParser = LiteralsParser;
function literal(isEqualToValue) {
return new parser_js_1.Parser(new LiteralsParser([isEqualToValue]));
}
exports.literal = literal;
function literals(firstValue, ...restValues) {
return new parser_js_1.Parser(new LiteralsParser([firstValue, ...restValues]));
}
exports.literals = literals;

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MappedAParser = void 0;
class MappedAParser {
constructor(parent, map, mappingName = map.name, description = {
name: "Mapped",
children: [parent],
extras: [mappingName],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "map", {
enumerable: true,
configurable: true,
writable: true,
value: map
});
Object.defineProperty(this, "mappingName", {
enumerable: true,
configurable: true,
writable: true,
value: mappingName
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
const map = this.map;
const result = this.parent.enumParsed(a);
if ("error" in result) {
return onParse.invalid(result.error);
}
return onParse.parsed(map(result.value));
}
}
exports.MappedAParser = MappedAParser;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaybeParser = void 0;
class MaybeParser {
constructor(parent, description = {
name: "Maybe",
children: [parent],
extras: [],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (a == null) {
return onParse.parsed(null);
}
// deno-lint-ignore no-this-alias
const parser = this;
const parentState = this.parent.enumParsed(a);
if ("error" in parentState) {
const { error } = parentState;
error.parser = parser;
return onParse.invalid(error);
}
return onParse.parsed(parentState.value);
}
}
exports.MaybeParser = MaybeParser;

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parserName = exports.NamedParser = void 0;
const index_js_1 = require("./index.js");
class NamedParser {
constructor(parent, name, description = {
name: "Named",
children: [parent],
extras: [name],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: name
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
// deno-lint-ignore no-this-alias
const parser = this;
const parent = this.parent.enumParsed(a);
if ("error" in parent) {
const { error } = parent;
error.parser = parser;
return onParse.invalid(error);
}
return onParse.parsed(parent.value);
}
}
exports.NamedParser = NamedParser;
function parserName(name, parent) {
return new index_js_1.Parser(new NamedParser(parent, name));
}
exports.parserName = parserName;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NilParser = void 0;
class NilParser {
constructor(description = {
name: "Null",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if (a === null || a === undefined)
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.NilParser = NilParser;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberParser = void 0;
const index_js_1 = require("./index.js");
class NumberParser {
constructor(description = {
name: "Number",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if ((0, index_js_1.isNumber)(a))
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.NumberParser = NumberParser;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectParser = void 0;
const utils_js_1 = require("./utils.js");
class ObjectParser {
constructor(description = {
name: "Object",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if ((0, utils_js_1.isObject)(a))
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.ObjectParser = ObjectParser;

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrParsers = void 0;
class OrParsers {
constructor(parent, otherParser, description = {
name: "Or",
children: [parent, otherParser],
extras: [],
}) {
Object.defineProperty(this, "parent", {
enumerable: true,
configurable: true,
writable: true,
value: parent
});
Object.defineProperty(this, "otherParser", {
enumerable: true,
configurable: true,
writable: true,
value: otherParser
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
// deno-lint-ignore no-this-alias
const parser = this;
const parent = this.parent.enumParsed(a);
if ("value" in parent) {
return onParse.parsed(parent.value);
}
const other = this.otherParser.enumParsed(a);
if ("error" in other) {
const { error } = other;
error.parser = parser;
return onParse.invalid(error);
}
return onParse.parsed(other.value);
}
}
exports.OrParsers = OrParsers;

View File

@@ -0,0 +1,296 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parser = void 0;
const index_js_1 = require("./index.js");
const utils_js_1 = require("../utils.js");
const any_parser_js_1 = require("./any-parser.js");
const array_parser_js_1 = require("./array-parser.js");
const bool_parser_js_1 = require("./bool-parser.js");
const concat_parser_js_1 = require("./concat-parser.js");
const default_parser_js_1 = require("./default-parser.js");
const function_parser_js_1 = require("./function-parser.js");
const guard_parser_js_1 = require("./guard-parser.js");
const mapped_parser_js_1 = require("./mapped-parser.js");
const maybe_parser_js_1 = require("./maybe-parser.js");
const named_js_1 = require("./named.js");
const nill_parser_js_1 = require("./nill-parser.js");
const number_parser_js_1 = require("./number-parser.js");
const object_parser_js_1 = require("./object-parser.js");
const or_parser_js_1 = require("./or-parser.js");
const shape_parser_js_1 = require("./shape-parser.js");
const string_parser_js_1 = require("./string-parser.js");
const utils_js_2 = require("./utils.js");
function unwrapParser(a) {
if (a instanceof Parser)
return unwrapParser(a.parser);
return a;
}
const enumParsed = {
parsed(value) {
return { value };
},
invalid(error) {
return { error };
},
};
/**
* A Parser is usually a function that takes a value and returns a Parsed value.
* For this class we have that as our main reason but we want to be able to have other methods
* including testing and showing text representations.
*
* The main function unsafeCast which will take in a value A (usually unknown) and will always return a B. If it cannot
* it will throw an error.
*
* The parse function is the lower level function that will take in a value and a dictionary of what to do with success and failure.
*/
class Parser {
constructor(parser, description = {
name: "Wrapper",
children: [parser],
extras: [],
}) {
Object.defineProperty(this, "parser", {
enumerable: true,
configurable: true,
writable: true,
value: parser
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
/// This is a hack to get the type of what the parser is going to return.
// deno-lint-ignore no-explicit-any
Object.defineProperty(this, "_TYPE", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
/**
* Use this as a guard clause, useful for escaping during the error cases.
* https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
* @param value
* @returns
*/
Object.defineProperty(this, "test", {
enumerable: true,
configurable: true,
writable: true,
value: (value) => {
return this.parse(value, utils_js_2.booleanOnParse);
}
});
}
/**
* Use this when you want to decide what happens on the succes and failure cases of parsing
* @param a
* @param onParse
* @returns
*/
parse(a, onParse) {
return this.parser.parse(a, onParse);
}
/**
* This is a constructor helper that can use a predicate tester in the form of a guard function,
* and will return a parser that will only parse if the predicate returns true.
* https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
* @param checkIsA
* @param name
* @returns
*/
static isA(checkIsA, name) {
return new Parser(new index_js_1.IsAParser(checkIsA, name));
}
/**
* Trying to convert the parser into a string representation
* @param parserComingIn
* @returns
*/
static parserAsString(parserComingIn) {
const parser = unwrapParser(parserComingIn);
const { description: { name, extras, children }, } = parser;
if (parser instanceof shape_parser_js_1.ShapeParser) {
return `${name}<{${parser.description.children
.map((subParser, i) => `${String(parser.description.extras[i]) || "?"}:${Parser.parserAsString(subParser)}`)
.join(",")}}>`;
}
if (parser instanceof or_parser_js_1.OrParsers) {
const parent = unwrapParser(parser.parent);
const parentString = Parser.parserAsString(parent);
if (parent instanceof or_parser_js_1.OrParsers)
return parentString;
return `${name}<${parentString},...>`;
}
if (parser instanceof guard_parser_js_1.GuardParser) {
return String(extras[0] || name);
}
if (parser instanceof string_parser_js_1.StringParser ||
parser instanceof object_parser_js_1.ObjectParser ||
parser instanceof number_parser_js_1.NumberParser ||
parser instanceof bool_parser_js_1.BoolParser ||
parser instanceof any_parser_js_1.AnyParser) {
return name.toLowerCase();
}
if (parser instanceof function_parser_js_1.FunctionParser) {
return name;
}
if (parser instanceof nill_parser_js_1.NilParser) {
return "null";
}
if (parser instanceof array_parser_js_1.ArrayParser) {
return "Array<unknown>";
}
const specifiers = [
...extras.map(utils_js_1.saferStringify),
...children.map(Parser.parserAsString),
];
const specifiersString = `<${specifiers.join(",")}>`;
return `${name}${specifiersString}`;
}
/**
* This is the most useful parser, it assumes the happy path and will throw an error if it fails.
* @param value
* @returns
*/
unsafeCast(value) {
const state = this.enumParsed(value);
if ("value" in state)
return state.value;
const { error } = state;
throw new TypeError(`Failed type: ${Parser.validatorErrorAsString(error)} given input ${(0, utils_js_1.saferStringify)(value)}`);
}
/**
* This is the like the unsafe parser, it assumes the happy path and will throw and return a failed promise during failure.
* @param value
* @returns
*/
castPromise(value) {
const state = this.enumParsed(value);
if ("value" in state)
return Promise.resolve(state.value);
const { error } = state;
return Promise.reject(new TypeError(`Failed type: ${Parser.validatorErrorAsString(error)} given input ${(0, utils_js_1.saferStringify)(value)}`));
}
/**
* When we want to get the error message from the input, to know what is wrong
* @param input
* @returns Null if there is no error
*/
errorMessage(input) {
const parsed = this.parse(input, enumParsed);
if ("value" in parsed)
return;
return Parser.validatorErrorAsString(parsed.error);
}
/**
* Use this that we want to do transformations after the value is valid and parsed.
* A use case would be parsing a string, making sure it can be parsed to a number, and then convert to a number
* @param fn
* @param mappingName
* @returns
*/
map(fn, mappingName) {
return new Parser(new mapped_parser_js_1.MappedAParser(this, fn, mappingName));
}
/**
* Use this when you want to combine two parsers into one. This will make sure that both parsers will run against the same value.
* @param otherParser
* @returns
*/
concat(otherParser) {
// deno-lint-ignore no-explicit-any
return new Parser(concat_parser_js_1.ConcatParsers.of(this, new Parser(otherParser)));
}
/**
* Use this to combine parsers into one. This will make sure that one or the other parsers will run against the value.
* @param otherParser
* @returns
*/
orParser(otherParser) {
return new Parser(new or_parser_js_1.OrParsers(this, new Parser(otherParser)));
}
/**
* When we want to make sure that we handle the null later on in a monoid fashion,
* and this ensures we deal with the value
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
*/
optional(_name) {
return new Parser(new maybe_parser_js_1.MaybeParser(this));
}
/**
* There are times that we would like to bring in a value that we know as null or undefined
* and want it to go to a default value
*/
defaultTo(defaultValue) {
return new Parser(new default_parser_js_1.DefaultParser(new Parser(new maybe_parser_js_1.MaybeParser(this)), defaultValue));
}
/**
* We want to test value with a test eg isEven
*/
validate(isValid, otherName) {
return new Parser(concat_parser_js_1.ConcatParsers.of(this, new Parser(new index_js_1.IsAParser(isValid, otherName))));
}
/**
* We want to refine to a new type given an original type, like isEven, or casting to a more
* specific type
*/
refine(refinementTest, otherName = refinementTest.name) {
return new Parser(concat_parser_js_1.ConcatParsers.of(this, new Parser(new index_js_1.IsAParser(refinementTest, otherName))));
}
/**
* Use this when we want to give the parser a name, and we want to be able to use the name in the error messages.
* @param nameString
* @returns
*/
name(nameString) {
return (0, named_js_1.parserName)(nameString, this);
}
/**
* This is another type of parsing that will return a value that is a discriminated union of the success and failure cases.
* https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions
* @param value
* @returns
*/
enumParsed(value) {
// deno-lint-ignore no-explicit-any
return this.parse(value, enumParsed);
}
/**
* Return the unwrapped parser/ IParser
* @returns
*/
unwrappedParser() {
// deno-lint-ignore no-this-alias no-explicit-any
let answer = this;
while (true) {
const next = answer.parser;
if (next instanceof Parser) {
answer = next;
}
else {
return next;
}
}
}
}
exports.Parser = Parser;
/**
* This is the line of code that could be over written if
* One would like to have a custom error as any shape
*/
Object.defineProperty(Parser, "validatorErrorAsString", {
enumerable: true,
configurable: true,
writable: true,
value: (error) => {
const { parser, value, keys } = error;
const keysString = !keys.length ? "" : keys
.map((x) => `[${x}]`)
.reverse()
.join("");
return `${keysString}${Parser.parserAsString(parser)}(${(0, utils_js_1.saferStringify)(value)})`;
}
});

View File

@@ -0,0 +1,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recursive = exports.RecursiveParser = void 0;
const parser_js_1 = require("./parser.js");
const simple_parsers_js_1 = require("./simple-parsers.js");
/**
* This parser is used when trying to create parsers that
* user their own definitions in their types, like interface Tree<Leaf> {
* [key: string]: Tree<Leaf> | Leaf;
* }
*/
class RecursiveParser {
static create(fn) {
const parser = new RecursiveParser(fn);
parser.parser = fn(new parser_js_1.Parser(parser));
return parser;
}
constructor(recursive, description = {
name: "Recursive",
children: [],
extras: [recursive],
}) {
Object.defineProperty(this, "recursive", {
enumerable: true,
configurable: true,
writable: true,
value: recursive
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
Object.defineProperty(this, "parser", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
parse(a, onParse) {
if (!this.parser) {
return onParse.invalid({
value: "Recursive Invalid State",
keys: [],
parser: this,
});
}
return this.parser.parse(a, onParse);
}
}
exports.RecursiveParser = RecursiveParser;
/**
* Must pass the shape that we expect since typescript as of this point
* can't infer with recursive functions like this.
* @param fn This should be a function that takes a parser, basically the self in a type recursion, and
* return a parser that is the combination of the recursion.
* @returns
*/
function recursive(fn) {
const value = fn(simple_parsers_js_1.any);
const created = RecursiveParser
.create(fn);
return new parser_js_1.Parser(created);
}
exports.recursive = recursive;

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shape = exports.isShape = exports.partial = exports.isPartial = exports.ShapeParser = void 0;
// deno-lint-ignore-file no-explicit-any ban-types
const index_js_1 = require("./index.js");
const utils_js_1 = require("../utils.js");
/**
* Given an object, we want to make sure the key exists and that the value on
* the key matches the parser
*/
class ShapeParser {
constructor(parserMap, isPartial, parserKeys = Object.keys(parserMap), description = {
name: isPartial ? "Partial" : "Shape",
children: parserKeys.map((key) => parserMap[key]),
extras: parserKeys,
}) {
Object.defineProperty(this, "parserMap", {
enumerable: true,
configurable: true,
writable: true,
value: parserMap
});
Object.defineProperty(this, "isPartial", {
enumerable: true,
configurable: true,
writable: true,
value: isPartial
});
Object.defineProperty(this, "parserKeys", {
enumerable: true,
configurable: true,
writable: true,
value: parserKeys
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
// deno-lint-ignore no-this-alias
const parser = this;
if (!index_js_1.object.test(a)) {
return onParse.invalid({
value: a,
keys: [],
parser,
});
}
const { parserMap, isPartial } = this;
const value = { ...a };
if (Array.isArray(a)) {
value.length = a.length;
}
for (const key in parserMap) {
if (key in value) {
const parser = parserMap[key];
const state = parser.enumParsed(a[key]);
if ("error" in state) {
const { error } = state;
error.keys.push((0, utils_js_1.saferStringify)(key));
return onParse.invalid(error);
}
const smallValue = state.value;
value[key] = smallValue;
}
else if (!isPartial) {
return onParse.invalid({
value: "missingProperty",
parser,
keys: [(0, utils_js_1.saferStringify)(key)],
});
}
}
return onParse.parsed(value);
}
}
exports.ShapeParser = ShapeParser;
const isPartial = (testShape) => {
return new index_js_1.Parser(new ShapeParser(testShape, true));
};
exports.isPartial = isPartial;
/**
* Good for duck typing an object, with optional values
* @param testShape Shape of validators, to ensure we match the shape
*/
exports.partial = exports.isPartial;
/**
* Good for duck typing an object
* @param testShape Shape of validators, to ensure we match the shape
*/
const isShape = (testShape) => {
return new index_js_1.Parser(new ShapeParser(testShape, false));
};
exports.isShape = isShape;
function shape(testShape, optionals, optionalAndDefaults) {
if (optionals) {
const defaults = optionalAndDefaults || {};
const entries = Object.entries(testShape);
const optionalSet = new Set(Array.from(optionals));
return (0, index_js_1.every)((0, exports.partial)(Object.fromEntries(entries
.filter(([key, _]) => optionalSet.has(key))
.map(([key, parser]) => [key, parser.optional()]))), (0, exports.isShape)(Object.fromEntries(entries.filter(([key, _]) => !optionalSet.has(key))))).map((ret) => {
for (const key of optionalSet) {
const keyAny = key;
if (!(keyAny in ret) && keyAny in defaults) {
ret[keyAny] = defaults[keyAny];
}
}
return ret;
});
}
return (0, exports.isShape)(testShape);
}
exports.shape = shape;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regex = exports.instanceOf = exports.string = exports.isArray = exports.object = exports.boolean = exports.isFunction = exports.natural = exports.isNill = exports.number = exports.unknown = exports.any = exports.guard = void 0;
const index_js_1 = require("./index.js");
const any_parser_js_1 = require("./any-parser.js");
const array_parser_js_1 = require("./array-parser.js");
const bool_parser_js_1 = require("./bool-parser.js");
const function_parser_js_1 = require("./function-parser.js");
const nill_parser_js_1 = require("./nill-parser.js");
const number_parser_js_1 = require("./number-parser.js");
const object_parser_js_1 = require("./object-parser.js");
const string_parser_js_1 = require("./string-parser.js");
const unknown_parser_js_1 = require("./unknown-parser.js");
/**
* Create a custom type guard
* @param test A function that will determine runtime if the value matches
* @param testName A name for that function, useful when it fails
*/
function guard(test, testName) {
return index_js_1.Parser.isA(test, testName || test.name);
}
exports.guard = guard;
exports.any = new index_js_1.Parser(new any_parser_js_1.AnyParser());
exports.unknown = new index_js_1.Parser(new unknown_parser_js_1.UnknownParser());
exports.number = new index_js_1.Parser(new number_parser_js_1.NumberParser());
exports.isNill = new index_js_1.Parser(new nill_parser_js_1.NilParser());
exports.natural = exports.number.refine((x) => x >= 0 && x === Math.floor(x));
exports.isFunction = new index_js_1.Parser(new function_parser_js_1.FunctionParser());
exports.boolean = new index_js_1.Parser(new bool_parser_js_1.BoolParser());
exports.object = new index_js_1.Parser(new object_parser_js_1.ObjectParser());
exports.isArray = new index_js_1.Parser(new array_parser_js_1.ArrayParser());
exports.string = new index_js_1.Parser(new string_parser_js_1.StringParser());
const instanceOf = (classCreator) => guard((x) => x instanceof classCreator, `is${classCreator.name}`);
exports.instanceOf = instanceOf;
const regex = (tester) => exports.string.refine(function (x) {
return tester.test(x);
}, tester.toString());
exports.regex = regex;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.some = void 0;
const simple_parsers_js_1 = require("./simple-parsers.js");
/**
* Union is a good tool to make sure that the validated value
* is in the union of all the validators passed in. Basically an `or`
* operator for validators.
*/
function some(...parsers) {
if (parsers.length <= 0) {
return simple_parsers_js_1.any;
}
const first = parsers.splice(0, 1)[0];
return parsers.reduce((left, right) => left.orParser(right), first);
}
exports.some = some;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringParser = void 0;
const utils_js_1 = require("./utils.js");
class StringParser {
constructor(description = {
name: "String",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
if ((0, utils_js_1.isString)(a))
return onParse.parsed(a);
return onParse.invalid({
value: a,
keys: [],
parser: this,
});
}
}
exports.StringParser = StringParser;

View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tuple = exports.TupleParser = void 0;
// deno-lint-ignore-file no-explicit-any
const index_js_1 = require("./index.js");
const utils_js_1 = require("../utils.js");
class TupleParser {
constructor(parsers, lengthMatcher = (0, index_js_1.literal)(parsers.length), description = {
name: "Tuple",
children: parsers,
extras: [],
}) {
Object.defineProperty(this, "parsers", {
enumerable: true,
configurable: true,
writable: true,
value: parsers
});
Object.defineProperty(this, "lengthMatcher", {
enumerable: true,
configurable: true,
writable: true,
value: lengthMatcher
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(input, onParse) {
const tupleError = index_js_1.isArray.enumParsed(input);
if ("error" in tupleError)
return onParse.invalid(tupleError.error);
const values = input;
const stateCheck = this.lengthMatcher.enumParsed(values.length);
if ("error" in stateCheck) {
stateCheck.error.keys.push((0, utils_js_1.saferStringify)("length"));
return onParse.invalid(stateCheck.error);
}
const answer = new Array(this.parsers.length);
for (const key in this.parsers) {
const parser = this.parsers[key];
const value = values[key];
const result = parser.enumParsed(value);
if ("error" in result) {
const { error } = result;
error.keys.push((0, utils_js_1.saferStringify)(key));
return onParse.invalid(error);
}
answer[key] = result.value;
}
return onParse.parsed(answer);
}
}
exports.TupleParser = TupleParser;
function tuple(...parsers) {
return new index_js_1.Parser(new TupleParser(parsers));
}
exports.tuple = tuple;

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnknownParser = void 0;
class UnknownParser {
constructor(description = {
name: "Unknown",
children: [],
extras: [],
}) {
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: description
});
}
parse(a, onParse) {
return onParse.parsed(a);
}
}
exports.UnknownParser = UnknownParser;

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.booleanOnParse = exports.empty = exports.isString = exports.isNumber = exports.isFunctionTest = exports.isObject = void 0;
const isObject = (x) => typeof x === "object" && x != null;
exports.isObject = isObject;
const isFunctionTest = (x) => typeof x === "function";
exports.isFunctionTest = isFunctionTest;
const isNumber = (x) => typeof x === "number";
exports.isNumber = isNumber;
const isString = (x) => typeof x === "string";
exports.isString = isString;
exports.empty = [];
exports.booleanOnParse = {
parsed(_) {
return true;
},
invalid(_) {
return false;
},
};

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saferStringify = void 0;
/**
* Tries and run the stringify, if that fails just return the toString
* @param x Could be anything, including a recursive object
*/
function saferStringify(x) {
try {
return JSON.stringify(x);
}
catch (e) {
return "" + x;
}
}
exports.saferStringify = saferStringify;

View File

@@ -0,0 +1,299 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Checker = exports.EmVer = exports.notRange = exports.rangeOr = exports.rangeAnd = exports.rangeOf = void 0;
const dependencies_js_1 = require("../dependencies.js");
const starSub = /((\d+\.)*\d+)\.\*/;
function incrementLastNumber(list) {
const newList = [...list];
newList[newList.length - 1]++;
return newList;
}
/**
* Will take in a range, like `>1.2` or `<1.2.3.4` or `=1.2` or `1.*`
* and return a checker, that has the check function for checking that a version is in the valid
* @param range
* @returns
*/
function rangeOf(range) {
return Checker.parse(range);
}
exports.rangeOf = rangeOf;
/**
* Used to create a checker that will `and` all the ranges passed in
* @param ranges
* @returns
*/
function rangeAnd(...ranges) {
if (ranges.length === 0) {
throw new Error("No ranges given");
}
const [firstCheck, ...rest] = ranges;
return Checker.parse(firstCheck).and(...rest);
}
exports.rangeAnd = rangeAnd;
/**
* Used to create a checker that will `or` all the ranges passed in
* @param ranges
* @returns
*/
function rangeOr(...ranges) {
if (ranges.length === 0) {
throw new Error("No ranges given");
}
const [firstCheck, ...rest] = ranges;
return Checker.parse(firstCheck).or(...rest);
}
exports.rangeOr = rangeOr;
/**
* This will negate the checker, so given a checker that checks for >= 1.0.0, it will check for < 1.0.0
* @param range
* @returns
*/
function notRange(range) {
return rangeOf(range).not();
}
exports.notRange = notRange;
/**
* EmVer is a set of versioning of any pattern like 1 or 1.2 or 1.2.3 or 1.2.3.4 or ..
*/
class EmVer {
/**
* Convert the range, should be 1.2.* or * into a emver
* Or an already made emver
* IsUnsafe
*/
static from(range) {
if (range instanceof EmVer) {
return range;
}
return EmVer.parse(range);
}
/**
* Convert the range, should be 1.2.* or * into a emver
* IsUnsafe
*/
static parse(range) {
const values = range.split(".").map((x) => parseInt(x));
for (const value of values) {
if (isNaN(value)) {
throw new Error(`Couldn't parse range: ${range}`);
}
}
return new EmVer(values);
}
constructor(values) {
Object.defineProperty(this, "values", {
enumerable: true,
configurable: true,
writable: true,
value: values
});
}
/**
* Used when we need a new emver that has the last number incremented, used in the 1.* like things
*/
withLastIncremented() {
return new EmVer(incrementLastNumber(this.values));
}
greaterThan(other) {
for (const i in this.values) {
if (other.values[i] == null) {
return true;
}
if (this.values[i] > other.values[i]) {
return true;
}
if (this.values[i] < other.values[i]) {
return false;
}
}
return false;
}
equals(other) {
if (other.values.length !== this.values.length) {
return false;
}
for (const i in this.values) {
if (this.values[i] !== other.values[i]) {
return false;
}
}
return true;
}
greaterThanOrEqual(other) {
return this.greaterThan(other) || this.equals(other);
}
lessThanOrEqual(other) {
return !this.greaterThan(other);
}
lessThan(other) {
return !this.greaterThanOrEqual(other);
}
/**
* Return a enum string that describes (used for switching/iffs)
* to know comparison
* @param other
* @returns
*/
compare(other) {
if (this.equals(other)) {
return "equal";
}
else if (this.greaterThan(other)) {
return "greater";
}
else {
return "less";
}
}
/**
* Used when sorting emver's in a list using the sort method
* @param other
* @returns
*/
compareForSort(other) {
return dependencies_js_1.matches.matches(this.compare(other))
.when("equal", () => 0)
.when("greater", () => 1)
.when("less", () => -1)
.unwrap();
}
}
exports.EmVer = EmVer;
/**
* A checker is a function that takes a version and returns true if the version matches the checker.
* Used when we are doing range checking, like saying ">=1.0.0".check("1.2.3") will be true
*/
class Checker {
/**
* Will take in a range, like `>1.2` or `<1.2.3.4` or `=1.2` or `1.*`
* and return a checker, that has the check function for checking that a version is in the valid
* @param range
* @returns
*/
static parse(range) {
if (range instanceof Checker) {
return range;
}
range = range.trim();
if (range.indexOf("||") !== -1) {
return rangeOr(...range.split("||").map((x) => Checker.parse(x)));
}
if (range.indexOf("&&") !== -1) {
return rangeAnd(...range.split("&&").map((x) => Checker.parse(x)));
}
if (range === "*") {
return new Checker((version) => {
EmVer.from(version);
return true;
});
}
if (range.startsWith("!")) {
return Checker.parse(range.substring(1)).not();
}
const starSubMatches = starSub.exec(range);
if (starSubMatches != null) {
const emVarLower = EmVer.parse(starSubMatches[1]);
const emVarUpper = emVarLower.withLastIncremented();
return new Checker((version) => {
const v = EmVer.from(version);
return (v.greaterThan(emVarLower) || v.equals(emVarLower)) &&
!v.greaterThan(emVarUpper) && !v.equals(emVarUpper);
});
}
switch (range.substring(0, 2)) {
case ">=": {
const emVar = EmVer.parse(range.substring(2));
return new Checker((version) => {
const v = EmVer.from(version);
return v.greaterThanOrEqual(emVar);
});
}
case "<=": {
const emVar = EmVer.parse(range.substring(2));
return new Checker((version) => {
const v = EmVer.from(version);
return v.lessThanOrEqual(emVar);
});
}
}
switch (range.substring(0, 1)) {
case ">": {
console.log("greaterThan");
const emVar = EmVer.parse(range.substring(1));
return new Checker((version) => {
const v = EmVer.from(version);
return v.greaterThan(emVar);
});
}
case "<": {
const emVar = EmVer.parse(range.substring(1));
return new Checker((version) => {
const v = EmVer.from(version);
return v.lessThan(emVar);
});
}
case "=": {
const emVar = EmVer.parse(range.substring(1));
return new Checker((version) => {
const v = EmVer.from(version);
return v.equals(emVar);
});
}
}
throw new Error("Couldn't parse range: " + range);
}
constructor(
/**
* Check is the function that will be given a emver or unparsed emver and should give if it follows
* a pattern
*/
check) {
Object.defineProperty(this, "check", {
enumerable: true,
configurable: true,
writable: true,
value: check
});
}
/**
* Used when we want the `and` condition with another checker
*/
and(...others) {
return new Checker((value) => {
if (!this.check(value)) {
return false;
}
for (const other of others) {
if (!Checker.parse(other).check(value)) {
return false;
}
}
return true;
});
}
/**
* Used when we want the `or` condition with another checker
*/
or(...others) {
return new Checker((value) => {
if (this.check(value)) {
return true;
}
for (const other of others) {
if (Checker.parse(other).check(value)) {
return true;
}
}
return false;
});
}
/**
* A useful example is making sure we don't match an exact version, like !=1.2.3
* @returns
*/
not() {
return new Checker((value) => !this.check(value));
}
}
exports.Checker = Checker;

View File

@@ -0,0 +1,239 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const dntShim = __importStar(require("../_dnt.test_shims.js"));
const mod_js_1 = require("../deps/deno.land/x/expect@v0.2.9/mod.js");
const mod_js_2 = require("./mod.js");
const { test } = dntShim.Deno;
{
const checker = (0, mod_js_2.rangeOf)("*");
test("rangeOf('*')", () => {
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(true);
});
test("rangeOf('*') invalid", () => {
(0, mod_js_1.expect)(() => checker.check("a")).toThrow();
(0, mod_js_1.expect)(() => checker.check("")).toThrow();
(0, mod_js_1.expect)(() => checker.check("1..3")).toThrow();
});
}
{
const checker = (0, mod_js_2.rangeOf)(">1.2.3.4");
test(`rangeOf(">1.2.3.4") valid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.5")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.4.1")).toBe(true);
});
test(`rangeOf(">1.2.3.4") invalid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
});
}
{
const checker = (0, mod_js_2.rangeOf)("=1.2.3");
test(`rangeOf("=1.2.3") valid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(true);
});
test(`rangeOf("=1.2.3") invalid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2")).toBe(false);
});
}
{
const checker = (0, mod_js_2.rangeOf)(">=1.2.3.4");
test(`rangeOf(">=1.2.3.4") valid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.5")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.4.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(true);
});
test(`rangeOf(">=1.2.3.4") invalid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
});
}
{
const checker = (0, mod_js_2.rangeOf)("<1.2.3.4");
test(`rangeOf("<1.2.3.4") invalid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.5")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.4.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(false);
});
test(`rangeOf("<1.2.3.4") valid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
});
}
{
const checker = (0, mod_js_2.rangeOf)("<=1.2.3.4");
test(`rangeOf("<=1.2.3.4") invalid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.5")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.4.1")).toBe(false);
});
test(`rangeOf("<=1.2.3.4") valid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(true);
});
}
{
const checkA = (0, mod_js_2.rangeOf)(">1");
const checkB = (0, mod_js_2.rangeOf)("<=2");
const checker = (0, mod_js_2.rangeAnd)(checkA, checkB);
test(`simple and(checkers) valid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.1")).toBe(true);
});
test(`simple and(checkers) invalid`, () => {
(0, mod_js_1.expect)(checker.check("2.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
(0, mod_js_1.expect)(checker.check("0")).toBe(false);
});
}
{
const checkA = (0, mod_js_2.rangeOf)("<1");
const checkB = (0, mod_js_2.rangeOf)("=2");
const checker = (0, mod_js_2.rangeOr)(checkA, checkB);
test(`simple or(checkers) valid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("0.1")).toBe(true);
});
test(`simple or(checkers) invalid`, () => {
(0, mod_js_1.expect)(checker.check("2.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.1")).toBe(false);
});
}
{
const checker = (0, mod_js_2.rangeOf)("1.2.*");
test(`rangeOf(1.2.*) valid`, () => {
(0, mod_js_1.expect)(checker.check("1.2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.1")).toBe(true);
});
test(`rangeOf(1.2.*) invalid`, () => {
(0, mod_js_1.expect)(checker.check("1.3")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.3.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.1.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.1")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
(0, mod_js_1.expect)(checker.check("2")).toBe(false);
});
}
{
const checker = (0, mod_js_2.notRange)((0, mod_js_2.rangeOf)("1.2.*"));
test(`notRange(rangeOf(1.2.*)) valid`, () => {
(0, mod_js_1.expect)(checker.check("1.3")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.3.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.1.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
});
test(`notRange(rangeOf(1.2.*)) invalid `, () => {
(0, mod_js_1.expect)(checker.check("1.2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.1")).toBe(false);
});
}
{
const checker = (0, mod_js_2.rangeOf)("!1.2.*");
test(`!(rangeOf(1.2.*)) valid`, () => {
(0, mod_js_1.expect)(checker.check("1.3")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.3.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.1.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
});
test(`!(rangeOf(1.2.*)) invalid `, () => {
(0, mod_js_1.expect)(checker.check("1.2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.1")).toBe(false);
});
}
{
test(`no and ranges`, () => {
(0, mod_js_1.expect)(() => (0, mod_js_2.rangeAnd)()).toThrow();
});
test(`no or ranges`, () => {
(0, mod_js_1.expect)(() => (0, mod_js_2.rangeOr)()).toThrow();
});
}
{
const checker = (0, mod_js_2.rangeOf)("!>1.2.3.4");
test(`rangeOf("!>1.2.3.4") invalid`, () => {
(0, mod_js_1.expect)(checker.check("2")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.5")).toBe(false);
(0, mod_js_1.expect)(checker.check("1.2.3.4.1")).toBe(false);
});
test(`rangeOf("!>1.2.3.4") valid`, () => {
(0, mod_js_1.expect)(checker.check("1.2.3.4")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.3")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
});
}
test(">1 && =1.2", () => {
const checker = (0, mod_js_2.rangeOf)(">1 && =1.2");
(0, mod_js_1.expect)(checker.check("1.2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.2.1")).toBe(false);
});
test("=1 || =2", () => {
const checker = (0, mod_js_2.rangeOf)("=1 || =2");
(0, mod_js_1.expect)(checker.check("1")).toBe(true);
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("3")).toBe(false);
});
test(">1 && =1.2 || =2", () => {
const checker = (0, mod_js_2.rangeOf)(">1 && =1.2 || =2");
(0, mod_js_1.expect)(checker.check("1.2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("3")).toBe(false);
});
test("&& before || order of operationns: <1.5 && >1 || >1.5 && <3", () => {
const checker = (0, mod_js_2.rangeOf)("<1.5 && >1 || >1.5 && <3");
(0, mod_js_1.expect)(checker.check("1.1")).toBe(true);
(0, mod_js_1.expect)(checker.check("2")).toBe(true);
(0, mod_js_1.expect)(checker.check("1.5")).toBe(false);
(0, mod_js_1.expect)(checker.check("1")).toBe(false);
(0, mod_js_1.expect)(checker.check("3")).toBe(false);
});
test("Compare function on the emver", () => {
const a = mod_js_2.EmVer.from("1.2.3");
const b = mod_js_2.EmVer.from("1.2.4");
(0, mod_js_1.expect)(a.compare(b) === "less");
(0, mod_js_1.expect)(b.compare(a) === "greater");
(0, mod_js_1.expect)(a.compare(a) === "equal");
});
test("Compare for sort function on the emver", () => {
const a = mod_js_2.EmVer.from("1.2.3");
const b = mod_js_2.EmVer.from("1.2.4");
(0, mod_js_1.expect)(a.compareForSort(b) === -1);
(0, mod_js_1.expect)(b.compareForSort(a) === 1);
(0, mod_js_1.expect)(a.compareForSort(a) === 0);
});

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